本文整理汇总了Java中org.bson.Document.parse方法的典型用法代码示例。如果您正苦于以下问题:Java Document.parse方法的具体用法?Java Document.parse怎么用?Java Document.parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.bson.Document
的用法示例。
在下文中一共展示了Document.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: executeInsert
import org.bson.Document; //导入方法依赖的package包/类
/**
* @param dbName 表名
* @param collectionName 集合名
* @param saveJson 待存入JSON
* @return 插入状态或异常信息
*/
@SuppressWarnings("unchecked")
public JSONObject executeInsert(String dbName, String collectionName, JSONObject saveJson) {
JSONObject resp = new JSONObject();
try {
MongoDatabase db = mongoClient.getDatabase(dbName);
MongoCollection coll = db.getCollection(collectionName);
Document doc = Document.parse(saveJson.toString());
coll.insertOne(doc);
} catch (MongoTimeoutException e1) {
e1.printStackTrace();
resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
return resp;
} catch (Exception e) {
e.printStackTrace();
resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
}
return resp;
}
示例2: 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;
}
示例3: transform
import org.bson.Document; //导入方法依赖的package包/类
@Override
public Document transform(Object from) {
try {
if (!(from instanceof String)) {
return Document.parse(objectMapper.writeValueAsString(from));
} else {
return Document.parse((String) from);
}
} catch (Exception ex) {
throw new TransformerException("Failed to transform content to Document!", ex);
}
}
示例4: insertEvent
import org.bson.Document; //导入方法依赖的package包/类
/**
* This method inserts an {@link Event} in the database
*
* @param event {@link Event} to insert into database
* @param callback {@link DatabaseWriterCallback} called after inserting
* @throws NullPointerException if event or callback is null
* @see DatabaseWriter#mongoCollection
* @see DatabaseWriter#LOCATION_FIELD
* @see DatabaseWriter#METRICS_LOGGER
* @see DatabaseWriter#mapper
*/
public void insertEvent(Event event, DatabaseWriterCallback callback) {
Objects.requireNonNull(event);
Objects.requireNonNull(callback);
try {
long start = System.currentTimeMillis();
Document document = Document.parse(mapper.writeValueAsString(event));
document.remove("start");
document.remove("end");
document.remove(LOCATION_FIELD);
document.append("start", event.getStart().getTime());
document.append("end", event.getEnd().getTime());
if (event.getLocation().length == 1) {
document.append(LOCATION_FIELD, new Point(new Position(
event.getLocation()[0].getLongitude(), event.getLocation()[0].getLatitude())));
} else {
List<Position> positions = Arrays.stream(event.getLocation())
.map(p -> new Position(p.getLongitude(), p.getLatitude())).collect(Collectors.toList());
document.append(LOCATION_FIELD, new Polygon(positions));
}
this.mongoCollection.insertOne(document, (result, t) -> callback.onResult(t));
long time = System.currentTimeMillis() - start;
METRICS_LOGGER.log("time_dbwriter_" + event.getSource(), time);
} catch (JsonProcessingException e) {
LOGGER.error("Invalid event format: event not inserted in database.");
}
}
示例5: createChange
import org.bson.Document; //导入方法依赖的package包/类
private MongoIndexChange createChange (CompoundIndex index, boolean replace){
Document definition = Document.parse(index.def());
IndexOptions opts = new IndexOptions();
opts.name(index.name());
opts.unique(index.unique());
opts.sparse(index.sparse());
opts.background(index.background());
return new MongoIndexChange(index.name(), definition, opts, replace);
}
示例6: executeUpsert
import org.bson.Document; //导入方法依赖的package包/类
/**
* @param dbName 库名
* @param collectionName 集合名
* @param json1 条件
* @param json2 保存doc
* @return upsert结果信息
*/
public JSONObject executeUpsert(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
JSONObject resp = new JSONObject();
try {
MongoDatabase db = mongoClient.getDatabase(dbName);
MongoCollection coll = db.getCollection(collectionName);
JSONObject saveJson = new JSONObject();
saveJson.put("$set", json2);
Document doc1 = Document.parse(json1.toString());
Document doc2 = Document.parse(saveJson.toString());
UpdateOptions up = new UpdateOptions();
up.upsert(true);
UpdateResult ur = coll.updateOne(doc1, doc2, up);
if (ur.isModifiedCountAvailable()) {
if (json1.containsKey(ID)) {
resp.put("Data", json1.get(ID));
} else {
resp.put("Data", json1);
}
}
} catch (MongoTimeoutException e1) {
e1.printStackTrace();
resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
return resp;
} catch (Exception e) {
e.printStackTrace();
resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
}
return resp;
}
示例7: executeUpdate
import org.bson.Document; //导入方法依赖的package包/类
/**
* @param dbName 库名
* @param collectionName 表名
* @param json1 条件
* @param json2 保存doc
* @return 更新结果信息
*/
public JSONObject executeUpdate(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
JSONObject resp = new JSONObject();
try {
MongoDatabase db = mongoClient.getDatabase(dbName);
MongoCollection coll = db.getCollection(collectionName);
JSONObject saveJson = new JSONObject();
saveJson.put("$set", json2);
Document doc1 = Document.parse(json1.toString());
Document doc2 = Document.parse(saveJson.toString());
UpdateResult ur = coll.updateOne(doc1, doc2);
System.out.println("doc1 = " + doc1.toString());
System.out.println("doc2 = " + doc2.toString());
if (ur.isModifiedCountAvailable()) {
if (json1.containsKey(ID)) {
resp.put("Data", json1.get(ID));
} else {
resp.put("Data", json1);
}
}
} catch (MongoTimeoutException e1) {
e1.printStackTrace();
resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
return resp;
} catch (Exception e) {
e.printStackTrace();
resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
}
return resp;
}
示例8: removeInfoFromConfigs
import org.bson.Document; //导入方法依赖的package包/类
/**
* @param info The push provider info to no longer persist.
*/
protected synchronized void removeInfoFromConfigs(final PushProviderInfo info) {
final Document configs = Document.parse(_globalPreferences.getString(PREF_CONFIGS, "{}"));
configs.remove(info.getService());
_globalPreferences.edit().putString(PREF_CONFIGS, configs.toJson()).apply();
}
示例9: postComment
import org.bson.Document; //导入方法依赖的package包/类
public boolean postComment(String body){
Document insert = new Document();
Document parsed = Document.parse(body);
commentCollection.insertOne(parsed);
return true;
}
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-2-spraguesanborn,代码行数:9,代码来源:FlowerController.java
示例10: incrementVisits
import org.bson.Document; //导入方法依赖的package包/类
public boolean incrementVisits(String body){
Document filter = new Document();
Document parsed = Document.parse(body);
filter.append("id", parsed.getString("plantID"));
flowerCollection.updateOne(filter, new Document("$inc", new Document("flowerVisits", 1)));
return true;
}
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-2-spraguesanborn,代码行数:9,代码来源:FlowerController.java
示例11: executeCount
import org.bson.Document; //导入方法依赖的package包/类
public JSONObject executeCount(String dbName, String collectionName, JSONObject reqJson) {
MongoDatabase db = mongoClient.getDatabase(dbName);
MongoCollection coll = db.getCollection(collectionName);
JSONObject resp = new JSONObject();
Document doc = Document.parse(reqJson.toString());
long count = coll.count(doc);
resp.put("Data", count);
return resp;
}
示例12: insertToMongo
import org.bson.Document; //导入方法依赖的package包/类
private void insertToMongo(String jsonString){
Document doc = Document.parse(jsonString);
mongoTemplate.insert(doc, "foo");
}
示例13: onTrigger
import org.bson.Document; //导入方法依赖的package包/类
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
ComponentLog logger = this.getLogger();
// Evaluate expression language and create BSON Documents
Document query = (queryProperty.isSet()) ? Document.parse(queryProperty.evaluateAttributeExpressions(flowFile).getValue()) : null;
Document projection = (projectionProperty.isSet()) ? Document.parse(projectionProperty.evaluateAttributeExpressions(flowFile).getValue()) : null;
Document sort = (sortProperty.isSet()) ? Document.parse(sortProperty.evaluateAttributeExpressions(flowFile).getValue()) : null;
try {
FindIterable<Document> it = (query != null) ? collection.find(query) : collection.find();
// Apply projection if needed
if (projection != null) {
it.projection(projection);
}
// Apply sort if needed
if (sort != null) {
it.sort(sort);
}
// Apply limit if set
if (limit != null) {
it.limit(limit.intValue());
}
// Iterate and create flowfile for each result
final MongoCursor<Document> cursor = it.iterator();
try {
while (cursor.hasNext()) {
// Create new flowfile with all parent attributes
FlowFile ff = session.clone(flowFile);
ff = session.write(ff, new OutputStreamCallback() {
@Override
public void process(OutputStream outputStream) throws IOException {
IOUtils.write(cursor.next().toJson(), outputStream);
}
});
session.transfer(ff, REL_SUCCESS);
}
} finally {
cursor.close();
session.remove(flowFile);
}
} catch (Exception e) {
logger.error("Failed to execute query {} due to {}.", new Object[]{query, e}, e);
flowFile = session.putAttribute(flowFile, "mongo.exception", e.getMessage());
session.transfer(flowFile, REL_FAILURE);
}
}
示例14: writeToPlantMetadataSheet
import org.bson.Document; //导入方法依赖的package包/类
/**
* Write plant metadata to the plant metadata sheet
* @param feedbackWriter
* @param uploadId
* @return
*/
public boolean writeToPlantMetadataSheet(FeedbackWriter feedbackWriter, String uploadId)
{
if (!ExcelParser.isValidUploadId(db, uploadId))
return false;
//Loop through all plants
FindIterable iter = plantCollection.find(
eq("uploadId", uploadId)
);
Iterator iterator = iter.iterator();
while (iterator.hasNext()) {
Document onPlant = (Document) iterator.next();
try {
String[] dataToWrite = new String[COL_PLANT_FIELDS];
Document metadata = (Document) onPlant.get("metadata");
Document feedback = Document.parse(getPlantFeedbackByPlantIdJSON(onPlant.getString("id"), uploadId));
Integer likeCount = feedback.getInteger("likeCount");
Integer dislikeCount = feedback.getInteger("dislikeCount");
Integer commentCount = feedback.getInteger("commentCount");
Integer pageViews = metadata.getInteger("pageViews");
dataToWrite[COL_PLANT_PLANTID] = onPlant.getString("id");
dataToWrite[COL_PLANT_COMMONNAME] = onPlant.getString("commonName");
dataToWrite[COL_PLANT_CULTIVAR] = onPlant.getString("cultivar");
dataToWrite[COL_PLANT_GRDNLOC] = onPlant.getString("gardenLocation");
dataToWrite[COL_PLANT_LIKES] = likeCount.toString();
dataToWrite[COL_PLANT_DISLIKES] = dislikeCount.toString();
dataToWrite[COL_PLANT_COMMENTS] = commentCount.toString();
dataToWrite[COL_PLANT_PAGEVIEWS] = pageViews.toString();
feedbackWriter.writeToSheet(dataToWrite, FeedbackWriter.SHEET_METADATA);
}
catch(Exception e)
{
e.printStackTrace();
System.err.println("ERROR ON PLANT " + onPlant);
}
}
return true;
}
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-revolverenguardia-1,代码行数:54,代码来源:PlantController.java
示例15: deleteOne
import org.bson.Document; //导入方法依赖的package包/类
private void deleteOne(){
Document doc = Document.parse(data.toString());
mcollection.deleteOne(doc);
}