Java Code Examples for org.bson.Document#append()

The following examples show how to use org.bson.Document#append() . 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: DocumentMemoryOperation.java    From jphp with Apache License 2.0 6 votes vote down vote up
@Override
public Document convert(Environment env, TraceInfo trace, Memory arg) throws Throwable {
    if (arg.isNull()) return null;

    ForeachIterator iterator = arg.getNewIterator(env);

    Document dbObject = new Document();

    while (iterator.next()) {
        if (iterator.getValue().isTraversable()) {
            dbObject.append(iterator.getStringKey(), convert(env, trace, iterator.getValue()));
        } else {
            dbObject.append(iterator.getStringKey(), Memory.unwrap(env, iterator.getValue()));
        }
    }

    return dbObject;
}
 
Example 2
Source File: GatewayDaoImpl.java    From redtorch with MIT License 6 votes vote down vote up
@Override
public void upsertGatewayByGatewayId(GatewayPo gateway) {
	if (gateway == null) {
		logger.error("根据网关ID更新或保存网关错误,参数gateway缺失");
		throw new IllegalArgumentException("根据网关ID更新或保存网关错误,参数gateway缺失");
	}
	if (StringUtils.isBlank(gateway.getGatewayId())) {
		logger.error("根据网关ID更新或保存网关错误,参数gatewayId缺失");
		throw new IllegalArgumentException("根据网关ID更新或保存网关错误,参数gatewayId缺失");
	}

	try {
		Document document = Document.parse(JSON.toJSONString(gateway));
		Document filter = new Document();
		filter.append("gatewayId", gateway.getGatewayId());
		managementDBClient.upsert(managementDBName, GATEWAY_COLLECTION_NAME, document, filter);
	} catch (IllegalArgumentException e) {
		logger.error("根据网关ID更新或保存网关错误", e);
	}

}
 
Example 3
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void createDocument(HashMap<String, Object> map) {

		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);

		Document doc = new Document();

		Iterator<String> keys = map.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			Object val = map.get(key);
			doc.append(key, val);
		}

		collection.insertOne(doc);

	}
 
Example 4
Source File: MongoCompensableRepository.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void markTransactionRollback(TransactionXid transactionXid) {
	try {
		byte[] global = transactionXid.getGlobalTransactionId();
		String identifier = ByteUtils.byteArrayToString(global);

		String application = CommonUtils.getApplication(this.endpoint);

		String databaseName = application.replaceAll("\\W", "_");
		MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
		MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS);

		Document document = new Document();
		document.append("$set", new Document("status", Status.STATUS_MARKED_ROLLBACK));

		Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, identifier);
		Bson statusFilter = Filters.eq("status", Status.STATUS_ACTIVE);

		collection.updateOne(Filters.and(globalFilter, statusFilter), document);
	} catch (RuntimeException error) {
		logger.error("Error occurred while setting the error flag.", error);
	}
}
 
Example 5
Source File: GatewayDaoImpl.java    From redtorch with MIT License 6 votes vote down vote up
@Override
public GatewayPo queryGatewayByGatewayId(String gatewayId) {
	if (StringUtils.isBlank(gatewayId)) {
		logger.error("根据网关ID查询网关错误,参数gatewayId缺失");
		throw new IllegalArgumentException("根据网关ID查询网关错误,参数gatewayId缺失");
	}

	Document filter = new Document();
	filter.append("gatewayId", gatewayId);
	List<Document> documentList = managementDBClient.find(managementDBName, GATEWAY_COLLECTION_NAME, filter);
	if (documentList == null || documentList.isEmpty()) {
		return null;
	}
	Document document = documentList.get(0);

	try {
		GatewayPo gateway = JSON.parseObject(JSON.toJSONString(document), GatewayPo.class);
		return gateway;
	} catch (Exception e) {
		logger.error("根据网关ID查询网关,数据转换发生错误Document-{}", document.toJson(), e);
		return null;
	}
}
 
Example 6
Source File: MongoPageSink.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<?> appendPage(Page page)
{
    MongoCollection<Document> collection = mongoSession.getCollection(schemaTableName);
    List<Document> batch = new ArrayList<>(page.getPositionCount());

    for (int position = 0; position < page.getPositionCount(); position++) {
        Document doc = new Document();

        for (int channel = 0; channel < page.getChannelCount(); channel++) {
            MongoColumnHandle column = columns.get(channel);
            doc.append(column.getName(), getObjectValue(columns.get(channel).getType(), page.getBlock(channel), position));
        }
        batch.add(doc);
    }

    collection.insertMany(batch, new InsertManyOptions().ordered(true));
    return NOT_BLOCKED;
}
 
Example 7
Source File: CompensableCleanupWork.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void forget(Xid xid, String resourceId) throws RuntimeException {
	try {
		String application = CommonUtils.getApplication(this.endpoint);
		String databaseName = application.replaceAll("\\W", "_");
		MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
		MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_REMOVEDRESES);

		byte[] global = xid.getGlobalTransactionId();
		byte[] branch = xid.getBranchQualifier();

		Document document = new Document();
		document.append(CONSTANTS_FD_GLOBAL, ByteUtils.byteArrayToString(global));
		document.append(CONSTANTS_FD_BRANCH, ByteUtils.byteArrayToString(branch));
		document.append("resource_id", resourceId);
		document.append("created", this.endpoint);

		collection.insertOne(document);
	} catch (RuntimeException error) {
		logger.error("Error occurred while forgetting resource({}).", resourceId, error);
	}
}
 
Example 8
Source File: SessionStorageMongoImpl.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Need to page the session out to Mongo
 * @param session
 */
public void onRequestEnd(cfSession Session) {
	cfSessionData	sessData	= getSessionData( Session );
	if ( sessData == null )
		return;

	try{
		Document	keys	= new Document("_id", appName + sessData.getStorageID() );
		Document	vals	= new Document("et", new Date(System.currentTimeMillis() + sessData.getTimeOut() ) );
		
		// Serialize the object
		ByteArrayOutputStreamRaw	bos	= new ByteArrayOutputStreamRaw( 32000 );
		FileUtil.saveClass(bos, sessData, true);

		byte[]	buf	= bos.toByteArray();

		// Has it really changed; we only update the last used date if it has
		if ( !MD5.getDigest(buf).equals( sessData.getMD5() ) )
			vals.append("d", buf);
		
		col.updateOne( keys, new Document("$set", vals), new UpdateOptions().upsert(true) );

	}catch(Exception e){
		cfEngine.log( appName + "MongoDBException: " + e );
	}
}
 
Example 9
Source File: MongoJobRepository.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
@Override
protected final Document encode(final JobInfo job) {
    final Document document = new Document()
            .append(JobStructure.ID.key(), job.getJobId())
            .append(JobStructure.JOB_TYPE.key(), job.getJobType())
            .append(JobStructure.STARTED.key(), Date.from(job.getStarted().toInstant()))
            .append(JobStructure.LAST_UPDATED.key(), Date.from(job.getLastUpdated().toInstant()))
            .append(JobStructure.MESSAGES.key(), job.getMessages().stream()
                    .map(MongoJobRepository::encodeJobMessage)
                    .collect(toList()))
            .append(JobStructure.STATUS.key(), job.getStatus().name())
            .append(JobStructure.HOSTNAME.key(), job.getHostname());
    if (job.isStopped()) {
        document.append(JobStructure.STOPPED.key(), Date.from(job.getStopped().get().toInstant()));
    }
    return document;
}
 
Example 10
Source File: DocumentConverter.java    From javers with Apache License 2.0 5 votes vote down vote up
static Document toDocument(JsonObject jsonObject) {
    Document document = new Document();

    for(Map.Entry<String,JsonElement> e : jsonObject.entrySet()) {
        document.append(e.getKey(), fromJsonElement(e.getValue()));
    }
    return document;
}
 
Example 11
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return a render parameters object for all tiles that match the specified criteria.
 *
 * @throws IllegalArgumentException
 *   if any required parameters are missing or the stack cannot be found.
 */
public RenderParameters getParameters(final StackId stackId,
                                      final String groupId,
                                      final Double x,
                                      final Double y,
                                      final Double z,
                                      final Integer width,
                                      final Integer height,
                                      final Double scale)
        throws IllegalArgumentException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("x", x);
    MongoUtil.validateRequiredParameter("y", y);
    MongoUtil.validateRequiredParameter("z", z);
    MongoUtil.validateRequiredParameter("width", width);
    MongoUtil.validateRequiredParameter("height", height);

    final double lowerRightX = x + width;
    final double lowerRightY = y + height;
    final Document tileQuery = getIntersectsBoxQuery(z, x, y, lowerRightX, lowerRightY);
    if (groupId != null) {
        tileQuery.append("groupId", groupId);
    }

    final RenderParameters renderParameters = new RenderParameters(null, x, y, width, height, scale);
    addResolvedTileSpecs(stackId, tileQuery, renderParameters);

    return renderParameters;
}
 
Example 12
Source File: AggregationPipelineImpl.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public AggregationPipeline unwind(final String field, final UnwindOptions options) {
    Document unwindOptions = new Document("path", "$" + field)
                                 .append("preserveNullAndEmptyArrays", options.isPreserveNullAndEmptyArrays());
    String includeArrayIndex = options.getIncludeArrayIndex();
    if (includeArrayIndex != null) {
        unwindOptions.append("includeArrayIndex", includeArrayIndex);
    }
    stages.add(new Document("$unwind", unwindOptions));
    return this;
}
 
Example 13
Source File: MongoPcjDocuments.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Adds binding set results to a specific PCJ.
 *
 * @param pcjId - Uniquely identifies a PCJ within Rya. (not null)
 * @param results - The binding set results. (not null)
 */
public void addResults(final String pcjId, final Collection<VisibilityBindingSet> results) {
    checkNotNull(pcjId);
    checkNotNull(results);

    final List<Document> pcjDocs = new ArrayList<>();
    for (final VisibilityBindingSet vbs : results) {
        // each binding gets it's own doc.
        final Document bindingDoc = new Document(PCJ_ID, pcjId);
        vbs.forEach(binding -> {
            final RyaType type = RdfToRyaConversions.convertValue(binding.getValue());
            bindingDoc.append(binding.getName(),
                    new Document()
                    .append(BINDING_TYPE, type.getDataType().stringValue())
                    .append(BINDING_VALUE, type.getData())
                    );
        });
        bindingDoc.append(VISIBILITIES_FIELD, vbs.getVisibility());
        pcjDocs.add(bindingDoc);
    }
    pcjCollection.insertMany(pcjDocs);

    // update cardinality in the metadata doc.
    final int appendCardinality = pcjDocs.size();
    final Bson query = new Document(PCJ_METADATA_ID, makeMetadataID(pcjId));
    final Bson update = new Document("$inc", new Document(CARDINALITY_FIELD, appendCardinality));
    pcjCollection.updateOne(query, update);
}
 
Example 14
Source File: DocumentTransferTool.java    From nuls-v2 with MIT License 5 votes vote down vote up
public static Document toDocument(Object obj, String _id) {
    if (null == obj) {
        return null;
    }
    Class clazz = obj.getClass();
    Field[] fields = clazz.getDeclaredFields();
    Document document = new Document();
    for (Field field : fields) {
        try {
            field.setAccessible(true);
            if ("isNew".equals(field.getName())) {
                continue;
            }
            if ("java.math.BigInteger".equals(field.getType().getName())) {
                BigInteger value = (BigInteger) field.get(obj);
                if (value == null) {
                    value = BigInteger.ZERO;
                }
                document.append(field.getName(), value.toString());
            } else if (field.getName().equals(_id)) {
                document.append("_id", field.get(obj));
            } else {
                document.append(field.getName(), field.get(obj));
            }
        } catch (IllegalAccessException e) {
            throw new NulsRuntimeException(ApiErrorCode.DATA_PARSE_ERROR, "Model to Document fail");
        }
    }
    return document;
}
 
Example 15
Source File: RestCommandController.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	Document doc = new Document();
	doc.append("exec_id", "cmd_0506");
	doc.append("data", "{\"actionType\":\"ringAlarm\",\"user_id\":\"S000001\",\"alarm_id\":\"1\"}");
	String json1 = doc.toJson();
	String json2 = "{ \"exec_id\": \"commandid\", \"data\": \"{\"actionType\":\"testAlarm\",\"user_id\":\"u00002\",\"alarm_id\":\"1\"}\"}";
	String json3 = "{ \"exec_id\": \"commandid\", \"data\": \"{\\\"actionType\\\":\\\"testAlarm\\\",\\\"user_id\\\":\\\"u00002\\\",\\\"alarm_id\\\":\\\"1\\\"}\"}";
	System.out.println(json1);
	System.out.println(Base64.encode(json1.getBytes()));
	System.out.println(json2);
	System.out.println(Base64.encode(json2.getBytes()));
	System.out.println(json3);
	System.out.println(Base64.encode(json3.getBytes()));
	
}
 
Example 16
Source File: SendTest.java    From medical-data-android with GNU General Public License v3.0 5 votes vote down vote up
private Document getDoc(Cursor c, ObjectId user_id, Boolean isFemale, Date date) throws java.text.ParseException {
    boolean drugs = (c.getInt(14) == 1);
    Document document = new Document()
            .append("user_id", user_id) // Check pinters
            .append("date", date) // Convert to date
            .append("speedReaction", new Document()
                    .append("last", c.getInt(1))
                    .append("total", c.getInt(2))
                    .append("tries", c.getInt(3)))
            .append("affectiveState", c.getInt(4))
            .append("motivation", c.getInt(5))
            .append("concentration", c.getInt(6))
            .append("anxiety", c.getInt(7))
            .append("irritability", c.getInt(8))
            .append("fatigue", c.getInt(9))
            .append("caffeine", c.getInt(11))
            .append("alcohol", c.getInt(12))
            .append("tobacco", c.getInt(13))
            .append("drugs", drugs)
            .append("timeBed", c.getInt(15))
            .append("timeSleep", c.getInt(16))
            .append("timeWakeUp", c.getInt(17))
            .append("latitude", c.getInt(18))
            .append("longitude", c.getInt(19));
    if (isFemale) {
        document.append("menstruation", c.getInt(10));
    }
    return document;
}
 
Example 17
Source File: RepositoryMinerExComment.java    From repositoryminer with Apache License 2.0 4 votes vote down vote up
@Override
public void mine(ExCommentConfig config) {
	if (config == null || !config.isValid()) {
		throw new RepositoryMinerException(
				"Invalid configuration, set the CSV files, the delimiter and a reference correctly.");
	}
	
	ISCM scm = SCMFactory.getSCM(repository.getScm());
	scm.open(repository.getPath());
	Commit commit = scm.resolve(config.getReference());
	scm.close();
       
       ExCommentDAO dao = new ExCommentDAO();
       dao.deleteByCommit(commit.getHash());
       
       ExCommentCSVReader csvReader = new ExCommentCSVReader(config);
       
       try {
           csvReader.readCSVs();
       } catch (IOException e) {
           throw new RepositoryMinerException("An IO error had occurred while reading the files.");
       }
       
       List<Document> documents = new ArrayList<Document>(csvReader.getFilesMap().size());
       for (Entry<String, List<Integer>> entry : csvReader.getFilesMap().entrySet()) {
           Document doc = new Document();
           
           doc.append("reference", config.getReference()).
               append("commit", commit.getHash()).
               append("commit_date", commit.getCommitterDate()).
               append("repository", repository.getId()).
               append("filename", entry.getKey()).
               append("filehash", StringUtils.encodeToCRC32(entry.getKey()));

           List<Comment> commentsAux = new ArrayList<Comment>(entry.getValue().size());
           for (Integer i : entry.getValue()) {
               commentsAux.add(csvReader.getCommentsMap().get(i));
           }
           doc.append("comments", Comment.toDocumentList(commentsAux));

           documents.add(doc);
       }

       dao.insertMany(documents);
	
}
 
Example 18
Source File: CommandResultDto.java    From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 4 votes vote down vote up
public String getTableBodyAsJson() {
    final Document doc = new Document();
    doc.append("content", tableBody.getTableRows());
    //doc.toJson();
    return com.mongodb.util.JSON.serialize(doc);
}
 
Example 19
Source File: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
private Document constructCompensablesDocument(TransactionArchive archive) throws IOException {
	List<CompensableArchive> compensableList = archive.getCompensableResourceList();
	Document compensables = new Document();
	for (int i = 0; compensableList != null && i < compensableList.size(); i++) {
		CompensableArchive resource = compensableList.get(i);

		Xid resourceXid = resource.getIdentifier();
		byte[] globalByteArray = resourceXid.getGlobalTransactionId();
		byte[] branchByteArray = resourceXid.getBranchQualifier();
		String globalKey = ByteUtils.byteArrayToString(globalByteArray);
		String branchKey = ByteUtils.byteArrayToString(branchByteArray);

		CompensableInvocation invocation = resource.getCompensable();
		String beanId = (String) invocation.getIdentifier();

		Method method = invocation.getMethod();
		Object[] args = invocation.getArgs();

		String methodDesc = SerializeUtils.serializeMethod(invocation.getMethod());
		byte[] argsByteArray = SerializeUtils.serializeObject(args);
		String argsValue = ByteUtils.byteArrayToString(argsByteArray);

		Document service = new Document();
		service.append(CONSTANTS_FD_GLOBAL, globalKey);
		service.append(CONSTANTS_FD_BRANCH, branchKey);

		// service.append("system", application);
		// service.append("created", this.endpoint);

		service.append("transaction_key", resource.getTransactionResourceKey());
		service.append("compensable_key", resource.getCompensableResourceKey());

		Xid transactionXid = resource.getTransactionXid();
		Xid compensableXid = resource.getCompensableXid();

		service.append("transaction_xid", String.valueOf(transactionXid));
		service.append("compensable_xid", String.valueOf(compensableXid));

		service.append("coordinator", resource.isCoordinator());
		service.append("tried", resource.isTried());
		service.append("confirmed", resource.isConfirmed());
		service.append("cancelled", resource.isCancelled());
		service.append("modified", this.endpoint);

		service.append("serviceId", beanId);
		service.append("simplified", invocation.isSimplified());
		service.append("confirmable_key", invocation.getConfirmableKey());
		service.append("cancellable_key", invocation.getCancellableKey());
		service.append("args", argsValue);
		service.append("interface", method.getDeclaringClass().getName());
		service.append("method", methodDesc);

		compensables.put(branchKey, service);
	}

	return compensables;
}
 
Example 20
Source File: OneM2MDmAdapter.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private Document callPostApi(String to, Document content) throws HitDMException, IOException {
/*	
	OneM2mRequest reqMessage = new OneM2mRequest();
	String json = content.toJson();
	reqMessage.setContent(json.getBytes());

	reqMessage.setTo(to);
	reqMessage.setOperation(OPERATION.CREATE);
	reqMessage.setContentType(CONTENT_TYPE.JSON);
	
	OneM2mResponse resMessage = HttpClient.getInstance().sendRequest(dmAddr+to, reqMessage);
	
	if (resMessage == null) {
		throw new HitDMException(5002, "Dm server does not respond:"+dmAddr+to);
	}

	if (resMessage.getHttpStatusCode() != 200) {
		String debugStr = "DM Server return:"+resMessage.getHttpStatusCode();
		byte[] body;
		try {
			body = resMessage.getContent();
			if (body != null) {
				debugStr += "\r\nBody:"+new String(body);
			}
		} catch (Exception e) {
			debugStr += e.getMessage();
		}
		
		throw new HitDMException(resMessage.getHttpStatusCode(), debugStr);
	}
	
	String resJson;
	try {
		
		resJson = new String(resMessage.getContent());
		
		Document resultDoc = Document.parse(resJson);
		
		return resultDoc; 
		
	} catch (Exception e) {

		log.debug("Handled exception", e);
		
		throw new HitDMException(5001, "Invalid response:"+resMessage.toString());			
		
	}
*/
	GenericHttpClient hc = new GenericHttpClient(dmAddr+to);
	hc.openConnection();
	hc.setRequestHeader();
	hc.setRequestMethod("POST");
	
	String result;
	try {
		hc.sendRequest(content.toJson());
		result = hc.getResponseString();
		
		Document resDoc = new Document();
		
		if(result.equalsIgnoreCase("OK")) {
			resDoc.append("result", "200");
			resDoc.append("message", "successful");
		} else {
			resDoc.append("result", "400");
			resDoc.append("message", "failure");
		}
		
		return resDoc;
	} catch(Exception e) {
		log.debug("Handled exception", e);
		throw new HitDMException(5001, "Invalid response:"+ e.toString());
	}
	
}