Java Code Examples for com.mongodb.BasicDBList#add()

The following examples show how to use com.mongodb.BasicDBList#add() . 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: DefaultGroupParser.java    From QueryBuilder with Apache License 2.0 6 votes vote down vote up
/**
 * 解析
 * @param group
 * @param parser
 * @return
 */
@Override
public Object parse(IGroup group, JsonRuleParser parser) {
    // rules
    BasicDBList operates = new BasicDBList();
    for (JsonRule jsonRule : group.getRules()) {
        operates.add(parser.parse(jsonRule));
    }

    // AND or OR
    BasicDBObject andOrObj = new BasicDBObject();
    andOrObj.append(EnumCondition.AND.equals(group.getCondition()) ? "$and" : "$or", operates);

    // Not
    if (group.getNot() != null && group.getNot()) {
        BasicDBList list = new BasicDBList();
        list.add(andOrObj);
        return new BasicDBObject("$nor", list);
    }
    return andOrObj;
}
 
Example 2
Source File: OrganismCompositionMongoWriter.java    From act with GNU General Public License v3.0 6 votes vote down vote up
private DBObject getDBObject() {
  DBObject o = new BasicDBObject();
  o.put("sname", standardName);
  o.put("names", names);
  if (cellularLoc != null) o.put("loc", cellularLoc);
  if (metacycURL != null) o.put("url", metacycURL);
  o.put("molw", molweight);
  BasicDBList reflist = new BasicDBList();
  for (String db : dbid.keySet()) {
    BasicDBObject ro = new BasicDBObject();
    ro.put("db", db);
    ro.put("id", dbid.get(db));
    reflist.add(ro);
  }
  o.put("refs", reflist);
  return o;
}
 
Example 3
Source File: AutomationStatistics.java    From XBDD with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 4
Source File: JsonTreeModel.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
private static DBObject buildDBList(NoSqlTreeNode parentNode) {
    BasicDBList basicDBList = new BasicDBList();
    Enumeration children = parentNode.children();
    while (children.hasMoreElements()) {
        NoSqlTreeNode node = (NoSqlTreeNode) children.nextElement();
        MongoValueDescriptor descriptor = (MongoValueDescriptor) node.getDescriptor();
        Object value = descriptor.getValue();
        if (value instanceof DBObject) {
            if (value instanceof BasicDBList) {
                basicDBList.add(buildDBList(node));
            } else {
                basicDBList.add(buildDBObject(node));
            }
        } else {
            basicDBList.add(value);
        }
    }
    return basicDBList;
}
 
Example 5
Source File: MongoDBToJSON.java    From act with GNU General Public License v3.0 6 votes vote down vote up
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;
  }
}
 
Example 6
Source File: MongoDbDeltaStoreUtil.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
public static DBObject 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;
}
 
Example 7
Source File: MongoDB.java    From act with GNU General Public License v3.0 6 votes vote down vote up
public DBIterator getIdCursorForFakeChemicals() {
  DBObject fakeRegex = new BasicDBObject();
  DBObject abstractInchi = new BasicDBObject();
  fakeRegex.put(ChemicalKeywords.INCHI$.MODULE$.toString(),
          new BasicDBObject(MongoKeywords.REGEX$.MODULE$.toString(), "^InChI=/FAKE"));

  abstractInchi.put(ChemicalKeywords.INCHI$.MODULE$.toString(),
          new BasicDBObject(MongoKeywords.REGEX$.MODULE$.toString(), "^InChI=.*R.*"));

  BasicDBList conditionList = new BasicDBList();
  conditionList.add(fakeRegex);
  conditionList.add(abstractInchi);

  BasicDBObject conditions = new BasicDBObject(MongoKeywords.OR$.MODULE$.toString(), conditionList);

  return getIteratorOverChemicals(conditions, new BasicDBObject(ChemicalKeywords.ID$.MODULE$.toString(), true));
}
 
Example 8
Source File: EqualCondition.java    From tangyuan2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setQuery(DBObject query, BasicDBList orList) {
	// if (null == orList) {
	// query.put(this.name, value.getValue());
	// } else {
	// orList.add(new BasicDBObject(this.name, value.getValue()));
	// }

	if (this.name.equals("_id")) {
		if (null == orList) {
			query.put(this.name, new ObjectId(value.getValue().toString()));
		} else {
			orList.add(new BasicDBObject(this.name, new ObjectId(value.getValue().toString())));
		}
	} else {
		if (null == orList) {
			query.put(this.name, value.getValue());
		} else {
			orList.add(new BasicDBObject(this.name, value.getValue()));
		}
	}
}
 
Example 9
Source File: EventParserTest.java    From ingestion with Apache License 2.0 6 votes vote down vote up
@Test
public void parseWithoutMapping() {
    final EventParser eventParser = new EventParser(MappingDefinition.load("/full_map.json"));
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("myString", "\"bar\""); // Overwrites the value defined in JSON body
    headers.put("myInt64", "64");
    headers.put("myBoolean", "true");
    headers.put("myDouble", "1.0");
    headers.put("myNull", "\"foobar\"");
    headers.put("myObj", "{ \"foo\": \"bar\" }");
    headers.put("myArr", "[1,1.0,\"str\"]");
    DBObject dbObject = eventParser.parse(EventBuilder.withBody(new byte[0], headers));
    assertThat(dbObject.get("myString")).isEqualTo("bar");
    assertThat(dbObject.get("myInt64"))
            .isEqualTo(64); // XXX: If auto-mapped, 64 will be recognized as int32, not int64
    assertThat(dbObject.get("myBoolean")).isEqualTo(true);
    assertThat(dbObject.get("myDouble")).isEqualTo(1.0);
    assertThat(dbObject.get("myNull")).isEqualTo("foobar");
    assertThat(dbObject.get("myObj")).isEqualTo(new BasicDBObject("foo", "bar"));
    BasicDBList dbList = new BasicDBList();
    dbList.add(1);
    dbList.add(1.0);
    dbList.add("str");
    assertThat(dbObject.get("myArr")).isEqualTo(dbList);
}
 
Example 10
Source File: MongodbInputDiscoverFieldsImplTest.java    From pentaho-mongodb-plugin with Apache License 2.0 6 votes vote down vote up
@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
}
 
Example 11
Source File: MongoDB.java    From act with GNU General Public License v3.0 5 votes vote down vote up
public List<Long> getRxnsWithSubstrate(String enzyme, Long org, List<Long> substrates) {
  BasicDBObject query = new BasicDBObject();
  query.put("organisms.id", org);
  BasicDBObject enzymeQuery = new BasicDBObject();
  enzymeQuery.put("ecnum", enzyme);
  query.put("$ne", enzymeQuery);
  for (Long substrate: substrates) {
    BasicDBList queryList = new BasicDBList();
    DBObject querySubstrate = new BasicDBObject();
    querySubstrate.put("enz_summary.substrates.pubchem", substrate);
    DBObject queryProduct = new BasicDBObject();
    queryProduct.put("enz_summary.products.pubchem", substrate);
    queryList.add(querySubstrate);
    queryList.add(queryProduct);
    query.put("$or", queryList);
  }

  DBCursor cur = this.dbReactions.find(query);
  List<Long> reactions = new ArrayList<Long>();
  while (cur.hasNext()) {
    DBObject o = cur.next();
    long id = (Integer) o.get("_id"); // checked: db type IS int
    reactions.add(id);
  }
  cur.close();
  return reactions;
}
 
Example 12
Source File: LessThanCondition.java    From tangyuan2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setQuery(DBObject query, BasicDBList orList) {
	if (null == orList) {
		query.put(this.name, new BasicDBObject("$lt", value.getValue()));
	} else {
		orList.add(new BasicDBObject(this.name, new BasicDBObject("$lt", value.getValue())));
	}
}
 
Example 13
Source File: MongoDB.java    From act with GNU General Public License v3.0 5 votes vote down vote up
public void updateReactionRefsOf(Seq seq) {
  BasicDBObject query = new BasicDBObject().append("_id", seq.getUUID());
  DBObject obj = this.dbSeq.findOne(query);
  BasicDBList refs = new BasicDBList();
  for (Long r : seq.getReactionsCatalyzed())
    refs.add(r);

  obj.put("rxn_refs", refs);
  this.dbSeq.update(query, obj);
}
 
Example 14
Source File: DescribableListConverter.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public Object encode(Object value, MappedField optionalExtraInfo) {
    if (value == null) return null;

    DescribableList describableList = (DescribableList) value;

    BasicDBList convertedList = new BasicDBList();

    for (Object obj : describableList.toList()) {
        convertedList.add(getMapper().toDBObject(obj));
    }

    return convertedList;
}
 
Example 15
Source File: AutomationStatistics.java    From XBDD with Apache License 2.0 5 votes vote down vote up
/**
 * Go through the prior versions of this product; for each version, find the latest build and contribute the stats for that to the
 * returned list.
 */
@GET
@Path("/recent-versions/{product}")
@Produces(MediaType.APPLICATION_JSON)
public Response getRecentVersionStatsForProduct(@BeanParam final Coordinates coordinates, @QueryParam("limit") final Integer limit) {
	final BasicDBList returns = new BasicDBList();

	final DBCollection summaryCollection = this.mongoLegacyDb.getCollection("summary");
	final DBCollection reportStatsCollection = this.mongoLegacyDb.getCollection("reportStats");
	final DBCursor versions = summaryCollection.find(coordinates.getQueryObject(Field.PRODUCT))
			.sort(Coordinates.getFeatureSortingObject());
	if (limit != null) {
		versions.limit(limit);
	}
	try {
		while (versions.hasNext()) { // go through each summary document
			final DBObject version = versions.next(); // each represents the coordinates for a given version
			final Coordinates c = new Coordinates((DBObject) version.get("coordinates"));
			final BasicDBList builds = (BasicDBList) version.get("builds");
			c.setBuild((String) builds.get(builds.size() - 1)); // we need to specify which build (the latest is last in the list)
			final DBObject query = c.getQueryObject();
			returns.add(reportStatsCollection.findOne(query));
		}
	} finally {
		versions.close();
	}

	return Response.ok(SerializerUtil.serialise(returns)).build();
}
 
Example 16
Source File: ContentInstanceAnncDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int deleteOldestNExpired(String containerId, int size) {
		
		log.debug("deleteOldestNExpired containerId:{}, size:{}", containerId, size);
		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		BasicDBList and = new BasicDBList();
		DeleteResult result;
		
		if (size >= 0) {
			and.clear();	
			and.add(new BasicDBObject(PARENTID_KEY, containerId));
			and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
			
			MongoCursor<Document> cursor = collection.find(new BasicDBObject("$and", and))
											.sort(new BasicDBObject(CREATETIME_KEY, 1))
											.limit(size).iterator();
			
			int deletedCount = 0;
			if (cursor.hasNext()) {
				Document doc = cursor.next();
//				and.clear();
//				and.add(new BasicDBObject(PARENTID_KEY, containerId));
//				and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
//				and.add(new BasicDBObject(CREATETIME_KEY, new BasicDBObject("$lt", doc.get(CREATETIME_KEY))));
//				
				result = collection.deleteOne(new BasicDBObject(RESID_KEY, doc.get(RESID_KEY)));
	
				deletedCount += result.getDeletedCount();
			}
			log.debug("Deleted oldest contentInstance:{}", deletedCount);
			return deletedCount;
		}
		return 0;
		
	}
 
Example 17
Source File: ContentInstanceAnncDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Resource retrieveLatest(String parentUri, RESULT_CONT resultContent) throws OneM2MException {		
	
	String now = LocalDateTime.now().toString(DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss"));

	DBObject c1 = new BasicDBObject(EXPIRETIME_KEY, null);
	DBObject c2 = new BasicDBObject(EXPIRETIME_KEY, new BasicDBObject("$gt", now));
	
	BasicDBList or = new BasicDBList();
	or.add(c1);
	or.add(c2);
	
	BasicDBObject query = new BasicDBObject("$or", or).append(PARENTID_KEY,  parentUri);
	
	List<Document>childList = getDocuments(query, RESOURCE_TYPE.CONTENT_INST, CREATETIME_KEY, false, 1);

	if (childList.size() == 0) {
		return null;
	}

	Document doc = childList.get(0);

	try {
		DaoJSONConvertor<ContentInstanceAnnc> cvt = (DaoJSONConvertor<ContentInstanceAnnc>)ConvertorFactory.getDaoJSONConvertor(ContentInstanceAnnc.class, ContentInstanceAnnc.SCHEMA_LOCATION);
		//DaoJSONConvertor<ContentInstance> cvt = new DaoJSONConvertor<ContentInstance>(ContentInstance.class);
		Resource res = (Resource) cvt.unmarshal(doc.toJson());
		res.setUri(doc.getString(URI_KEY));
		
		return res;
	} catch (Exception e) {
		log.debug("Handled exception", e);
		
		throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR, "Exception during initialization of resource using document.(retrieveOldest)");
	}
	
}
 
Example 18
Source File: GroupResource.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
@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();
}
 
Example 19
Source File: Presence.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@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();

}
 
Example 20
Source File: MongoClient.java    From pandaria with MIT License 5 votes vote down vote up
private BasicDBList toList(MongoCursor<Document> iterator) {
    BasicDBList list = new BasicDBList();
    while (iterator.hasNext()) {
        list.add(iterator.next());
    }
    return list;
}