下面列出了怎么用com.mongodb.BasicDBList的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
@SuppressWarnings("unchecked")
public String getTenantEdOrg(String lzPath) {
NeutralQuery query = new NeutralQuery(new NeutralCriteria(LANDING_ZONE_PATH, "=", lzPath));
Entity entity = entityRepository.findOne(TENANT_COLLECTION, query);
if ( null == entity ) {
return null;
}
Map<String, Object> body = entity.getBody();
if ( null == body ) {
return null;
}
BasicDBList lzArr = (BasicDBList) body.get(LANDING_ZONE);
if ( null == lzArr ) {
return null;
}
for( Object lzObj : lzArr ) {
Map<String, Object> lz = (Map<String, Object>) lzObj;
String path = (String) lz.get(PATH);
if ( null != path && path.equals(lzPath) ) {
return (String) lz.get(EDUCATION_ORGANIZATION);
}
}
return null;
}
public static void readFieldFromDb(String fieldKey, String range,
Annotation a, Feature f, BasicDBObject dbO, JCas jCas) {
if (dbO.containsField(fieldKey)) {
if (range.equals("String")) {
a.setStringValue(f, dbO.getString(fieldKey));
} else if (range.equals("StringArray")) {
BasicDBList vals = (BasicDBList) dbO.get(fieldKey);
StringArray sa = new StringArray(jCas, vals.size());
for (int i = 0; i < vals.size(); i++) {
sa.set(i, vals.get(i).toString());
}
a.setFeatureValue(f, sa);
} else if (range.equals("Integer")) {
a.setIntValue(f, dbO.getInt(fieldKey));
} else if (range.equals("Float")) {
a.setFloatValue(f, (float) dbO.getDouble(fieldKey));
} else if (range.equals("Boolean")) {
a.setBooleanValue(f, dbO.getBoolean(fieldKey));
} else {
LOG.warn("range not supported " + range);
}
}
}
public static DBObject conv(JSONArray a) {
BasicDBList result = new BasicDBList();
try {
for (int i = 0; i < a.length(); ++i) {
Object o = a.get(i);
if (o instanceof JSONObject) {
result.add(conv((JSONObject)o));
} else if (o instanceof JSONArray) {
result.add(conv((JSONArray)o));
} else {
result.add(o);
}
}
return result;
} catch (JSONException je) {
return null;
}
}
/**
* Uses the '.+' regexp on featureId to allow for symbols such as slashes in the id
*
* @param featureId String The featureId to make changes to
* @return DBObjet Returns the the features new state if changes were made and returns null if bad JSON was sent
*/
@PUT
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response putFeature(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
final BasicDBObject feature) {
feature.put("calculatedStatus", StatusHelper.getFeatureStatus(feature));
final DBCollection collection = this.mongoLegacyDb.getCollection("features");
final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
final DBObject report = collection.findOne(example);
// get the differences/new edits
// Detect if the edits caused a change
feature.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
feature.put("lastEditOn", new Date());
final BasicDBList edits = updateEdits(feature, report);
feature.put("edits", edits);
updateTestingTips(this.mongoLegacyDb, coordinates, featureId, feature); // save testing tips / strip them out of the document.
updateEnvironmentDetails(this.mongoLegacyDb, coordinates, feature);
collection.save(feature);
Feature.embedTestingTips(feature, coordinates, this.mongoLegacyDb); // rembed testing tips.
return Response.ok(SerializerUtil.serialise(feature))
.build();// pull back feature - will re-include tips that were extracted prior to saving
}
public static BasicDBObject serialize(TransformedWaveletDelta transformedWaveletDelta) {
BasicDBObject mongoTransformedWaveletDelta = new BasicDBObject();
mongoTransformedWaveletDelta.append(FIELD_AUTHOR,
serialize(transformedWaveletDelta.getAuthor()));
mongoTransformedWaveletDelta.append(FIELD_RESULTINGVERSION,
serialize(transformedWaveletDelta.getResultingVersion()));
mongoTransformedWaveletDelta.append(FIELD_APPLICATIONTIMESTAMP,
transformedWaveletDelta.getApplicationTimestamp());
mongoTransformedWaveletDelta.append(FIELD_APPLIEDATVERSION,
transformedWaveletDelta.getAppliedAtVersion());
BasicDBList mongoWaveletOperations = new BasicDBList();
for (WaveletOperation op : transformedWaveletDelta) {
mongoWaveletOperations.add(serialize(op));
}
mongoTransformedWaveletDelta.append(FIELD_OPS, mongoWaveletOperations);
return mongoTransformedWaveletDelta;
}
static DBObject[] getSecondaryObjectSets( DBObject exprObj )
{
if( !(exprObj instanceof BasicDBList) )
return null; // no secondary element(s)
BasicDBList objList = (BasicDBList)exprObj;
if( objList.size() <= 1 )
return null;
// return the second and remaining DBObject(s) from the list
List<DBObject> secondaryObjList = new ArrayList<DBObject>(objList.size()-1);
for( int i=1; i < objList.size(); i++ )
{
Object value = objList.get(i);
if( value instanceof DBObject )
secondaryObjList.add( (DBObject)value );
else // ignore elements that are not DBObject
logInvalidTagValue( value );
}
if( secondaryObjList.isEmpty() )
return null;
return (DBObject[])secondaryObjList.toArray( new DBObject[secondaryObjList.size()] );
}
@Override
public BasicDBObject getTimeRangeQuery(
Object sourceId, long timeStart, long minTime) {
if(sourceId == null){
// All sources across the time range, cannot use the id index
return new BasicDBObject(ID_TIME_KEY, new BasicDBObject("$lte", timeStart).append("$gte", minTime));
} else if( sourceId instanceof BasicDBList){
// Create a query from the id components rather than the id itself
return new BasicDBObject(ID_SOURCE_KEY, new BasicDBObject("$in", sourceId)).append(
ID_TIME_KEY, new BasicDBObject("$lte", timeStart).append("$gte", minTime));
} else {
// Single sourceId, construct a more optimal ID query for this case
BasicDBObject startId = new BasicDBObject(
Sample.SOURCE_KEY, sourceId).append(Sample.TS_KEY, timeStart);
BasicDBObject minId = new BasicDBObject(
Sample.SOURCE_KEY, sourceId).append(Sample.TS_KEY, minTime);
return new BasicDBObject("$lte", startId).append("$gte", minId);
}
}
/**
* Create a Mongo DB Object baed on the content of this group
*
* @param id The Mongo Object id to assign to this DB Object. If null, a new Object id will be
* created
* @return - The Mongo DB Object based on the content of this group
*/
public BasicDBObject getDBObject(boolean includeId) {
BasicDBObject group = new BasicDBObject();
if (includeId) {
group.append(DB_ID, new ObjectId(id));
}
group.append(JSON_KEY_GROUP_NAME, name);
BasicDBList membersArray = new BasicDBList();
for (int i = 0; i < members.length; i++) {
membersArray.add(members[i]);
}
group.append(JSON_KEY_MEMBERS_LIST, membersArray);
return group;
}
public Set<SearchResult> getTopSearchResultsFromCache(String name) {
Set<SearchResult> searchResults = new HashSet<>();
String formattedName = name.toLowerCase();
BasicDBObject nameSearchResultDBObject = bingCacheMongoDB.getNameSearchResultDBObjectFromName(formattedName);
if (nameSearchResultDBObject == null) {
return searchResults;
}
BasicDBList topSearchResultsList = (BasicDBList) nameSearchResultDBObject.get("topSearchResults");
if (topSearchResultsList == null) {
return searchResults;
}
for (Object topSearchResult : topSearchResultsList) {
SearchResult searchResult = new SearchResult();
BasicDBObject topSearchResultDBObject = (BasicDBObject) topSearchResult;
searchResult.populateFromBasicDBObject(topSearchResultDBObject);
searchResults.add(searchResult);
}
return searchResults;
}
/**
* Get the game data from database as a double value array.
* If it does not exist in database, or is illegal, return an empty double array.
*
* @param key
* @param defaultValue
* @return
*/
public double[] getGameDataAsDoubleArray(GameDataKey key) {
Object obj = getValueFromDatabase(key);
if ( obj == NULL ) {
return new double[0];
} else if ( obj instanceof double[] ) {
return (double[])obj;
} else {
BasicDBList list = (BasicDBList)obj;
double[] array = new double[list.size()];
for ( int i=0; i<array.length; i++ ) {
array[i] = (Double)list.get(i);
}
return array;
}
}
@Test
public void shouldPushToChannel() throws Exception {
String feedName = "feed1";
String channelName = "channel1";
Channel channel = getConfiguredChannel(null, feedName, channelName);
BasicDBObject sample = new BasicDBObject(Sample.TS_KEY, 100L);
sample.append(Sample.DATA_KEY, new BasicDBObject("v", 1));
channel.pushSample(sample, false, new BasicDBList());
// get the sample by id
List<Sample> samples = channel.query(null, 200, 150, null, null, 50);
assertEquals(samples.size(), 1);
Sample found = samples.get(0);
assertEquals(found.getTimeStamp(), 100);
}
@Test public void testDiscoverFieldsNestedArray() throws Exception {
setupPerform();
BasicDBObject doc = new BasicDBObject();
BasicDBList list = new BasicDBList();
list.add( new BasicDBObject( "bar", BigDecimal.valueOf( 123.123 ) ) );
Date date = new Date();
list.add( new BasicDBObject( "fap", date ) );
doc.put( "foo", list );
doc.put( "baz", new BasicDBObject( "bop", new BasicDBObject( "fop", false ) ) );
when( cursor.next() ).thenReturn( doc );
List<MongoField> fields =
discoverFields
.discoverFields( new MongoProperties.Builder(), "mydb", "mycollection", "", "", false, NUM_DOCS_TO_SAMPLE,
inputMeta );
validateFields( fields,
"bar", "foo.0.bar", 123.123, // field 0
"fap", "foo.1.fap", date, // field 1
"fop", "baz.bop.fop", "stringValue" ); // field 2
}
@Test
public void testInterceptorOrdering() throws Exception {
String feedName = "feed3";
String channelName = "channel1";
String configPath = "plugin_config/interceptor_ordering.json";
// Try to configure
Channel channel = getConfiguredChannel(configPath, feedName, channelName);
BasicDBObject sample = new BasicDBObject(Sample.TS_KEY, 100L);
sample.append(Sample.DATA_KEY, new BasicDBObject("v", 240));
channel.pushSample(sample, false, new BasicDBList());
List<Sample> recalled = channel.query(null, 1000, 1000, null, null, 1);
// The interceptors should have added the field x and then posted the values [2,1]
BasicDBList testList = (BasicDBList) recalled.get(0).getData().get("x");
assertEquals(testList.get(0), 2);
assertEquals(testList.get(1), 1);
}
@Override
public void pushSample(DBObject sample, boolean isList, BasicDBList resultIds) {
if(sample != null && isList){
for(Object sampleObj : (BasicDBList)sample){
validate((BasicDBObject) sampleObj, resultIds);
}
}
else{
validate((BasicDBObject)sample, resultIds);
}
// Call forward the interceptor chain
this.next.pushSample(sample, isList, resultIds);
}
public <T> List<T> getList(String itemName, Class<T> listOf) {
List<T> list = new ArrayList<T>();
Object itemObj = rawDocument.get(itemName);
if(itemObj != null){
// Must be a list
if(itemObj instanceof BasicDBList){
BasicDBList rawList = (BasicDBList)itemObj;
for(Object listEntry : rawList){
list.add(fromObject(itemName, listOf, listEntry));
}
}
else{
throw new ServiceException("Config item is not List",
ConfigurationError.INVALID_CONFIG_TYPE).
set("configuring", targetClass).
set(itemName, itemObj).
set("expectedListOf", listOf);
}
}
// If the item doesnt exist
return list;
}
@GET
@Path("/recent-builds/{product}")
public Response getRecentBuildStatsForProduct(@BeanParam final Coordinates coordinates, @QueryParam("limit") final Integer limit) {
final BasicDBList returns = new BasicDBList();
final DBCollection collection = this.mongoLegacyDb.getCollection("reportStats");
final BasicDBObject example = coordinates.getQueryObject(Field.PRODUCT);
final DBCursor cursor = collection.find(example).sort(Coordinates.getFeatureSortingObject());
if (limit != null) {
cursor.limit(limit);
}
try {
while (cursor.hasNext()) {
final DBObject doc = cursor.next();
returns.add(doc);
}
} finally {
cursor.close();
}
return Response.ok(SerializerUtil.serialise(returns)).build();
}
/**
* Get the game data from database as a int value array.
* If it does not exist in database, or is illegal, return an empty double array.
*
* @param key
* @param defaultValue
* @return
*/
public int[] getGameDataAsIntArray(GameDataKey key) {
Object obj = getValueFromDatabase(key);
if ( obj == NULL ) {
return new int[0];
} else if ( obj instanceof double[] ) {
return (int[])obj;
} else {
BasicDBList list = (BasicDBList)obj;
int[] array = new int[list.size()];
for ( int i=0; i<array.length; i++ ) {
array[i] = (Integer)list.get(i);
}
return array;
}
}
@Test
public void testPreSplit() {
List<DBObject> shards = new ArrayList<DBObject>();
shards.add(new BasicDBObject("_id", "shard0"));
shards.add(new BasicDBObject("_id", "shard1"));
BasicDBList listShards = new BasicDBList();
listShards.add(new BasicDBObject("shards", shards));
List<String> lShards = new ArrayList<String>();
lShards.add("shard0");
lShards.add("lShard1");
Mockito.when(db.command((DBObject) Matchers.any())).thenReturn(res);
Mockito.when(res.get("shards")).thenReturn(listShards);
String result = MongoCommander.preSplit(shardCollections, dbName, mockedMongoTemplate);
assertNull(result);
Mockito.verify(db, Mockito.times(1)).command(new BasicDBObject("enableSharding", dbName));
Mockito.verify(db, Mockito.times(2)).command(new BasicDBObject("listShards", 1));
//Verify total number of mongo command calls
Mockito.verify(db, Mockito.times(13)).command(Matchers.any(DBObject.class));
//For setBalancerState
Mockito.verify(settings, Mockito.times(1)).update(Matchers.any(DBObject.class), Matchers.any(DBObject.class), Matchers.eq(true), Matchers.eq(false));
}
private void fanoutContent(final List<User> followers, final Content content){
BasicDBList contentList = new BasicDBList();
contentList.add(content.toDBObject());
// Build list of target users
BasicDBList followerIds = new BasicDBList();
for(User user : followers) {
followerIds.add(user.getUserId());
}
// Push to the cache of all followers, note that upsert is set to
// true so that if there is no cache for a user it does not create
// it (intentionally)
final BasicDBObject query = findMany(ContentCache.CACHE_OWNER_KEY, followerIds);
final BasicDBObject update = pushToCappedArray(
ContentCache.CACHE_TIMELINE_KEY, contentList, config.cache_size_limit);
this.cacheCollection.update(query, update, false, true);
}
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);
}
@POST
@Path("/{feed}/{channel}/data")
public String pushToChannel(
@PathParam("feed") String feedId,
@PathParam("channel") String channelId,
@QueryParam("sample") JSONParam sample ) {
// Find the correct channel implementation
Channel channel = channelService.getChannel(feedId, channelId);
// push it to the channel correct
DBObject sampleObj = sample.toDBObject();
BasicDBList sid = new BasicDBList();
channel.pushSample(sampleObj, sampleObj instanceof BasicDBList, sid);
// return the ID
return JSON.serialize(sid);
}
public Set<Long> getOrganismIDs(Long reactionID) {
if (reactionID < 0) {
reactionID = Reaction.reverseID(reactionID);
}
DBObject query = new BasicDBObject();
query.put("_id", reactionID);
Set<Long> ids = new HashSet<Long>();
DBObject reaction = this.dbReactions.findOne(query);
if (reaction != null) {
BasicDBList orgs = (BasicDBList) reaction.get("organisms");
for(Object o : orgs) {
ids.add((Long)((DBObject) o).get("id")); // checked: db type IS long
}
}
return ids;
}
public Seq convertDBObjectToSeq(DBObject o) {
long id = (Integer)o.get("_id"); // checked: db type IS int
String ecnum = (String)o.get("ecnum");
String org_name = (String)o.get("org");
Long org_id = (Long)o.get("org_id");
String aa_seq = (String)o.get("seq");
String srcdb = (String)o.get("src");
BasicDBList refs = (BasicDBList)o.get("references");
DBObject meta = (DBObject)o.get("metadata");
BasicDBList rxn_refs = (BasicDBList) (o.get("rxn_refs"));
if (srcdb == null) srcdb = Seq.AccDB.swissprot.name();
Seq.AccDB src = Seq.AccDB.valueOf(srcdb); // genbank | uniprot | trembl | embl | swissprot
List<JSONObject> references = new ArrayList<>();
if (refs != null) for (Object r : refs) references.add(MongoDBToJSON.conv((DBObject) r));
String dummyString = ""; // for type differentiation in overloaded method
Long dummyLong = 0L; // for type differentiation in overloaded method
Set<Long> rxns_catalyzed = from_dblist(rxn_refs, dummyLong);
return Seq.rawInit(id, ecnum, org_id, org_name, aa_seq, references, meta, src,
// the rest of the params are the ones that are typically
// "constructed". But since we are reading from the DB, we manually init
rxns_catalyzed
);
}
private BasicDBList toList(MongoCursor<Document> iterator) {
BasicDBList list = new BasicDBList();
while (iterator.hasNext()) {
list.add(iterator.next());
}
return list;
}
public List<Reaction> getRxnsWithAll(List<Long> reactants, List<Long> products) {
if (reactants.size() == 0 && products.size() == 0) {
throw new IllegalArgumentException("Reactants and products both empty! Query would return entire DB.");
}
BasicDBObject query = new BasicDBObject();
if (!reactants.isEmpty()) {
BasicDBList substrateIds = new BasicDBList();
substrateIds.addAll(reactants);
query.put("enz_summary.substrates.pubchem", new BasicDBObject("$all", substrateIds));
}
if (!products.isEmpty()) {
BasicDBList productIds = new BasicDBList();
productIds.addAll(products);
query.put("enz_summary.products.pubchem", new BasicDBObject("$all", productIds));
}
DBCursor cur = this.dbReactions.find(query);
List<Reaction> reactions = new ArrayList<Reaction>();
try {
while (cur.hasNext()) {
DBObject o = cur.next();
reactions.add(convertDBObjectToReaction(o));
}
} finally {
cur.close();
}
return reactions;
}
public static BasicDBObject pushToCappedArray(
final String fieldKey, final BasicDBList items, final int limit) {
return new BasicDBObject("$push",
new BasicDBObject(fieldKey,
new BasicDBObject("$each", items)
.append("$slice", -limit)));
}
public static List<Contribution> dbListToList(BasicDBList dbl) {
String method = "dbListToList";
logger.entering(clazz, method, dbl);
List<Contribution> contributions = new ArrayList<>();
for (Object dbo : ListUtils.emptyIfNull(dbl)) {
contributions.add(new Contribution((BasicDBObject) dbo));
}
logger.exiting(clazz, method, listToString(contributions));
return contributions;
}
@PUT
@Path("/build/{product}/{major}.{minor}.{servicePack}/{build}")
@Produces(MediaType.APPLICATION_JSON)
public Response addBuildToRecents(@BeanParam final Coordinates coordinates) {
final DBObject buildCoords = coordinates.getReportCoordinates();
final DBCollection collection = this.mongoLegacyDb.getCollection("users");
final BasicDBObject user = new BasicDBObject();
user.put("user_id", LoggedInUserUtil.getLoggedInUser().getUserId());
final DBObject blank = new BasicDBObject();
final DBObject doc = collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true, true);
if (doc.containsField("recentBuilds")) {
final BasicDBList buildArray = (BasicDBList) doc.get("recentBuilds");
if (buildArray.contains(buildCoords)) {
// BasicDBObject toMove = (BasicDBObject) featureArray.get(featureArray.indexOf(featureDetails));
buildArray.remove(buildCoords);
buildArray.add(buildCoords);
collection.update(user, new BasicDBObject("$set", new BasicDBObject("recentBuilds", buildArray)));
} else {
if (buildArray.size() >= 5) {
collection.update(user, new BasicDBObject("$pop", new BasicDBObject("recentBuilds", "-1")));
}
collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentBuilds", buildCoords)));
}
} else {
collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentBuilds", buildCoords)));
}
return Response.ok().build();
}
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response getGroups(@QueryParam("userId") String userId) {
// Validate the JWT. At this point, anyone can get a group list if they
// have a valid JWT.
try {
validateJWT();
} catch (JWTException jwte) {
return Response.status(Status.UNAUTHORIZED)
.type(MediaType.TEXT_PLAIN)
.entity(jwte.getMessage())
.build();
}
DBCursor groupCursor = null;
BasicDBList groupList = new BasicDBList();
if (userId != null) {
if (!ObjectId.isValid(userId)) {
return Response.status(Status.BAD_REQUEST)
.type(MediaType.TEXT_PLAIN)
.entity("The user id provided is not valid.")
.build();
}
BasicDBObject queryObj = new BasicDBObject(Group.JSON_KEY_MEMBERS_LIST, userId);
groupCursor = getGroupCollection().find(queryObj);
} else {
groupCursor = getGroupCollection().find();
}
while (groupCursor.hasNext()) {
groupList.add((new Group(groupCursor.next()).getJson()));
}
String responsePayload = (new BasicDBObject(Group.JSON_KEY_GROUPS, groupList)).toString();
return Response.ok(responsePayload).build();
}
@GET
@Path("/{product}/{major}.{minor}.{servicePack}/{build}")
@Produces(MediaType.APPLICATION_JSON)
public Response getPresencesForBuild(@BeanParam final Coordinates coordinates) {
final DBCollection collection = this.mongoLegacyDb.getCollection("presence");
final BasicDBObject query = coordinates.getQueryObject(Field.PRODUCT, Field.VERSION, Field.BUILD);
final BasicDBList presencesForBuild = new BasicDBList();
final DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
presencesForBuild.add(cursor.next());
}
return Response.ok(SerializerUtil.serialise(presencesForBuild)).build();
}