本文整理汇总了Java中org.bson.Document类的典型用法代码示例。如果您正苦于以下问题:Java Document类的具体用法?Java Document怎么用?Java Document使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Document类属于org.bson包,在下文中一共展示了Document类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: insertUsingDocument
import org.bson.Document; //导入依赖的package包/类
/**
* This method insert the document using Document object
*/
@Override
public void insertUsingDocument() {
MongoDatabase db = null;
MongoCollection collection = null;
try {
db = client.getDatabase(mongo.getDataBase());
collection = db.getCollection(mongo.getSampleCollection());
Document obj1 = new Document();
obj1.put("name", "Sivaraman");
obj1.put("age", 23);
obj1.put("gender", "male");
collection.insertOne(obj1);
log.info("Document Insert Successfully using Document Obj...");
} catch (MongoException | ClassCastException e) {
log.error("Exception occurred while insert Value using **Document** : " + e, e);
}
}
示例2: retryEvent
import org.bson.Document; //导入依赖的package包/类
public SyncEvent retryEvent(ObjectId eventId, boolean retryFailed, boolean retryEntire, boolean dropCollection) {
Document updateQuery = new Document();
updateQuery.append("$set", new Document(SyncAttrs.STATUS, SyncStatus.PENDING).append(SyncAttrs.IS_RETRY, true))
.append("$unset", new Document(SyncAttrs.ERRORS, true).append(SyncAttrs.MARKER, true));
if (retryFailed) {
syncEvents.updateMany(
Filters.and(Filters.eq(SyncAttrs.PARENT_EVENT_ID, eventId),
Filters.eq(SyncAttrs.STATUS, SyncStatus.FAILED), Filters.ne(SyncAttrs.ID, eventId)),
updateQuery);
syncEvents.updateOne(Filters.eq(SyncAttrs.ID, eventId),
Updates.set(SyncAttrs.STATUS, SyncStatus.IN_PROGRESS));
} else {
if (retryEntire) {
syncEvents.updateMany(Filters.eq(SyncAttrs.PARENT_EVENT_ID, eventId),
Updates.set(SyncAttrs.STATUS, SyncStatus.CANCELLED));
syncEvents.updateOne(Filters.eq(SyncAttrs.ID, eventId), updateQuery);
}
}
return getEvent(eventId);
}
示例3: decode
import org.bson.Document; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public O2MSyncEventLog decode(BsonReader arg0, DecoderContext arg1) {
Document document = documentCodec.decode(arg0, arg1);
O2MSyncEventLog log = new O2MSyncEventLog();
log.setLogId(document.getObjectId(_ID));
log.setEventId(document.getString(EVENT_ID));
log.setCrOn(document.getDate(CREATED_ON));
log.setSyOn(document.getDate(SYNCED_ON));
log.setStatus(document.getString(STATUS));
log.setOperation(document.getString(OPERATION));
List<Document> filterDocList = (List<Document>) document.get(EVENT_FILTERS);
if(filterDocList!=null){
List<O2MSyncEventInfo> filters = new ArrayList<O2MSyncEventInfo>(filterDocList.size());
O2MSyncEventInfo filter = null;
for(Document filterDoc : filterDocList){
filter= new O2MSyncEventInfo();
filter.setTableName(filterDoc.getString(TABLE_NAME));
filter.setColumnName(filterDoc.getString(COLUMN_NAME));
filter.setColumnValue(filterDoc.get(COLUMN_VALUE));
filters.add(filter);
}
log.setEventFilters(filters);
}
return log;
}
示例4: listPlants
import org.bson.Document; //导入依赖的package包/类
public String listPlants(Map<String, String[]> queryParams, String uploadId) {
Document filterDoc = new Document();
filterDoc.append("uploadId", uploadId);
if (queryParams.containsKey("gardenLocation")) {
String location = (queryParams.get("gardenLocation")[0]);
filterDoc = filterDoc.append("gardenLocation", location);
}
if (queryParams.containsKey("commonName")) {
String commonName = (queryParams.get("commonName")[0]);
filterDoc = filterDoc.append("commonName", commonName);
}
FindIterable<Document> matchingPlants = plantCollection.find(filterDoc);
return JSON.serialize(matchingPlants);
}
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-3-sixguysburgers-fries,代码行数:21,代码来源:PlantController.java
示例5: find
import org.bson.Document; //导入依赖的package包/类
/**
* 查找指定条数的数据
*/
public List<Map<String, Object>> find(String collectionName, Integer pageNumber, Integer pageSize) {
MongoCollection collection = mongoDatabase.getCollection(collectionName);
List<Map<String, Object>> list = new ArrayList<>();
if (collection == null) {
return list;
}
FindIterable findIterable = collection.find();
if (pageSize != null && pageSize >= 0) {
if (pageNumber != null && pageNumber >= 1) {
findIterable = findIterable.skip((pageNumber - 1) * pageSize);
}
findIterable = findIterable.limit(pageSize);
}
Iterator<Document> iterator = findIterable.iterator();
while (iterator.hasNext()) {
Document document = iterator.next();
document.remove("_id");
Map<String, Object> map = new HashMap<>(document);
list.add(map);
}
return list;
}
示例6: getGardenLocations
import org.bson.Document; //导入依赖的package包/类
/**
* Returns an array of Strings of all garden locations for the current uploadId
* sorted according to the BedComparator
* @param uploadID
* @return
*/
public String[] getGardenLocations(String uploadID){
if (!ExcelParser.isValidUploadId(db, uploadID))
return null;
//Get distinct gardenLocations for this uploadId
Document filter = new Document();
filter.append("uploadId", uploadID);
DistinctIterable<String> bedIterator = plantCollection.distinct("gardenLocation", filter, String.class);
List<String> beds = new ArrayList<String>();
for(String s : bedIterator)
{
beds.add(s);
}
//Then sort the gardenLocations as according to BedComparator
beds.sort(new BedComparator());
return beds.toArray(new String[beds.size()]);
}
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-revolverenguardia-1,代码行数:25,代码来源:PlantController.java
示例7: encodeJoinedTable
import org.bson.Document; //导入依赖的package包/类
private Document encodeJoinedTable(JoinedTable joinedTable) {
Document document = new Document();
document.append(SyncAttrs.JOIN_TYPE, String.valueOf(joinedTable.getJoinType()));
document.append(SyncAttrs.FILTERS, encodeFilters(joinedTable.getFilters()));
OracleTable innerJoinedTable = joinedTable.getTable();
document.append(SyncAttrs.TABLE_NAME, innerJoinedTable.getTableName());
document.append(SyncAttrs.TABLE_ALIAS, innerJoinedTable.getTableAlias());
if (innerJoinedTable.getJoinedTables() != null) {
List<Document> nestedJoinedTableList = new ArrayList<Document>();
for (JoinedTable nestedJoinedTable : innerJoinedTable.getJoinedTables()) {
nestedJoinedTableList.add(encodeJoinedTable(nestedJoinedTable));
}
document.append(SyncAttrs.JOINED_TABLES, nestedJoinedTableList);
}
return document;
}
示例8: append
import org.bson.Document; //导入依赖的package包/类
/**
* Appends an operator with simple pairs
*
* @param operator The operator
* @param pairs The pairs of key/value for this operator
* @return This
*/
public MongoQuery append(Operator operator, Keyable... pairs) {
String key = "$" + operator.getName();
Document document = documentMap.containsKey(key) ? documentMap.get(key) : new Document();
for(Keyable p : pairs) {
String pKey = p.getKey();
if(p instanceof KeyMultiValue) {
for(Object o : ((KeyMultiValue) p).getValues()) {
document.append(pKey, o);
}
}
else if(p instanceof KeyValue) {
document.append(pKey, ((KeyValue) p).getVal());
}
}
documentMap.put(key, document);
return this;
}
示例9: toComplexes
import org.bson.Document; //导入依赖的package包/类
/**
* Converts the list of messages into a list of elements of given class
* This method is only for complex classes like {@link PlayerData}<br>
* <p>
* A really common pitfall is using the class for the same index of the respond list for this method,
* because this method counts different.
* e.g.: Respond list is: PlayerData, Group, PlayerData
* Means the index is: 0 0 1
*
* @param eClass The element's class
* @param <E> The element type
* @return The list
*/
public <E> List<E> toComplexes(Class<E> eClass) throws MooInputException {
this.checkState();
if(complexElementMap.containsKey(eClass)) return complexElementMap.get(eClass);
List<E> l = new ArrayList<>();
DataArchitecture architecture = DataArchitecture.fromClass(eClass);
DataResolver dataResolver = new DataResolver(architecture);
for(String msg : getMessageAsList()) {
E e;
if(DESERIALIZED_PATTERN.matcher(msg).matches()) {
e = ReflectionUtil.deserialize(msg, eClass);
}
else {
// list the document from the message
// create object from this
Document document = Document.parse(msg);
e = dataResolver.doc(document).complete(eClass);
}
if(e != null) l.add(e);
}
complexElementMap.put(eClass, l);
return l;
}
示例10: withDateTimeLiteral
import org.bson.Document; //导入依赖的package包/类
@Test
public void withDateTimeLiteral() {
String expression =
format("createdAt < '%s'", DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()));
List<Document> documents = toList(repository.find(dataset, "", expression, "", -1));
assertThat(documents.size(), is(2));
assertThat(documents, hasItem(bill));
assertThat(documents, hasItem(martin));
expression =
format("createdAt > '%s'", DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()));
documents = toList(repository.find(dataset, "", expression, "", -1));
assertThat(documents.size(), is(0));
}
示例11: configure
import org.bson.Document; //导入依赖的package包/类
private void configure() {
MongoDatabase db = this.mongoClient.getDatabase(dbName);
MongoCollection<Document> metadataColl = db.getCollection(METADATA_COLL_NAME);
if (metadataColl.count() > 1) {
throw new IndraError("Model metadata must have only one entry!");
}
if (metadataColl.count() == 1) {
logger.debug("Using stored metadata of {}", dbName);
Document storedMetadata = metadataColl.find().first();
metadata = ModelMetadata.createFromMap(storedMetadata);
}
else {
logger.debug("No metadata found in {}, using defaults.", dbName);
metadata = ModelMetadata.createDefault();
}
logger.info("Model metadata: {}", metadata);
}
示例12: queryClientState
import org.bson.Document; //导入依赖的package包/类
/**
* Get the current ClientState of a client,
* connected or not.
* @param uuid The UUID of the client. This must be a valid
* UUID which belongs to a client. If the UUID is
* not found in the database or connected clients,
* then a RuntimeException is thrown.
* @return The ClientState of the specified client with the UUID.
*/
public ClientState queryClientState(String uuid) {
for(ClientSession session : this.sessions.values()) {
if(session.getToken().getUuid().equals(uuid)) {
return session.getState();
}
}
// The session is not currently connected, so we need to check the database
MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
Document doc = clients.find(Filters.eq("uuid", uuid)).first();
if(doc != null) {
return ClientState.fromInt(doc.getInteger("state", ClientState.UNKNOWN.toInt()));
}
// We couldn't find the client in the database, so throw an exception
throw new RuntimeException("Failed to find UUID " + uuid + "in connected sessions or in database. Is it invalid?");
}
示例13: findAll
import org.bson.Document; //导入依赖的package包/类
@Override
public List<Migration> findAll() {
List<Migration> migrations = new ArrayList<>();
collection.find()
.forEach((Consumer<Document>) d ->
migrations.add(
new Migration(
d.getString("version"),
d.getString("description"),
d.getString("author"),
Optional.ofNullable(d.getDate("started")).map(DateTime::new).orElse(null),
Optional.ofNullable(d.getDate("finished")).map(DateTime::new).orElse(null),
MigrationStatus.valueOf(d.getString("status")),
d.getString("failureMessage")
)
)
);
return migrations;
}
示例14: saveconnectionInfo
import org.bson.Document; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public void saveconnectionInfo(String jsonStr) {
Document document = parsefromJson(jsonStr);
SyncConnectionInfo connectionInfo = new SyncConnectionInfo();
if(document.getObjectId(ID)!=null){
connectionInfo.setConnectionId(document.getObjectId(ID));
}
String dbType = document.getString(DBTYPE);
connectionInfo.setDbType(dbType);
connectionInfo.setDbName(document.getString(DBNAME));
connectionInfo.setUserName(document.getString(USERNAME));
connectionInfo.setPassword(document.getString(PASSWORD));
if(dbType!=null && dbType.equalsIgnoreCase("Mongo")){
Map<String,Double> hostToPortMap = new HashMap<String,Double>();
List<Document> hostToPort = (List<Document>) document.get(HOSTTOPORTMAP);
for(Document doc : hostToPort){
hostToPortMap.put(doc.getString(HOST), doc.getDouble(PORT));
}
connectionInfo.setHostToPortMap(hostToPortMap);
}
connectionDao.updateConnection(connectionInfo);
}
示例15: encodeOracleToMongoGridFsMap
import org.bson.Document; //导入依赖的package包/类
public void encodeOracleToMongoGridFsMap(OracleToMongoGridFsMap map, Document document) {
logger.debug("Encode called for MongoObject");
if (null != map.getCollectionName() && !map.getCollectionName().isEmpty()) {
document.append(SyncAttrs.ATTRIBUTE_NAME, map.getCollectionName());
}
Map<String, ColumnAttrMapper> mapperListMap = map.getMetaAttributes();
if (mapperListMap != null && !mapperListMap.isEmpty()) {
List<Document> mapperListDoc = new ArrayList<Document>();
for (Map.Entry<String, ColumnAttrMapper> mapperEntry : mapperListMap.entrySet()) {
mapperListDoc.add(encodeColumnAttrMapper(mapperEntry.getValue()));
}
document.append(SyncAttrs.META_ATTRIBUTES, new Document(SyncAttrs.ATTRIBUTES, mapperListDoc));
}
document.append(SyncAttrs.FILE_NAME_COLUMN, encodeColumn(map.getFileNameColumn()));
document.append(SyncAttrs.INPUT_STREAM_COLUMN, encodeColumn(map.getInputStreamColumn()));
if(map.getStreamTable() != null)
document.append(SyncAttrs.STREAM_TABLE, encodeTable(map.getStreamTable()));
if (map.getFilters() != null) {
document.append(SyncAttrs.FILTERS, encodeFilters(map.getFilters()));
}
logger.debug("Encoded Document : " + document);
}