Java Code Examples for com.mongodb.DBObject#toString()

The following examples show how to use com.mongodb.DBObject#toString() . 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: MongoDataHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private Map<String, Map<String, DataColumn>> generateTableMetaData() {
    int ordinalPosition = 1;
    Map<String, Map<String, DataColumn>> metaData = new HashMap<>();
    HashMap<String, DataColumn> column = new HashMap<>();
    for (String tableName : this.tableList) {
        DBCollection readResult = jongo.getDatabase().getCollection(tableName);
        Iterator<DBObject> cursor = readResult.find();
        while (cursor.hasNext()) {
            DBObject doumentData = cursor.next();
            String tempValue = doumentData.toString();
            Iterator<?> keys = new JSONObject(tempValue).keys();
            while (keys.hasNext()) {
                String columnName = (String) keys.next();
                DataColumn dataColumn = new DataColumn(columnName, DataColumn.ODataDataType.STRING,
                                                       ordinalPosition, true, 100, columnName.equals(DOCUMENT_ID));
                column.put(columnName, dataColumn);
                ordinalPosition++;
            }
            metaData.put(tableName, column);
        }
    }
    return metaData;
}
 
Example 2
Source File: MongoDataHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This method reads the data for a given collection.
 * Returns a list of DataEntry objects.
 *
 * @param tableName Name of the table
 * @return EntityCollection
 * @see DataEntry
 */
@Override
public List<ODataEntry> readTable(String tableName) {
    List<ODataEntry> entryList = new ArrayList<>();
    DBCollection readResult = jongo.getDatabase().getCollection(tableName);
    Iterator<DBObject> cursor = readResult.find();
    DBObject documentData;
    String tempValue;
    while (cursor.hasNext()) {
        ODataEntry dataEntry;
        documentData = cursor.next();
        tempValue = documentData.toString();
        Iterator<?> keys = new JSONObject(tempValue).keys();
        dataEntry = createDataEntryFromResult(tempValue, keys);
        //Set Etag to the entity
        dataEntry.addValue(ETAG, ODataUtils.generateETag(this.configId, tableName, dataEntry));
        entryList.add(dataEntry);
    }
    return entryList;
}
 
Example 3
Source File: ProjectResource.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public Representation doRepresent() {
	String projectId = (String) getRequest().getAttributes().get("projectid");
	
	ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository();
	
	// FIXME: This exclusion list needs to be somewhere... 
	BasicDBObject ex = new BasicDBObject("executionInformation", 0);
	ex.put("storage", 0);
	ex.put("metricProviderData", 0);
	ex.put("_superTypes", 0);
	ex.put("_id", 0);
	
	// FIXME: Temporary solution to DBRefs not being expanded
	// How can we auto-expand and DBRefs when serialising?
	ex.put("licenses", 0);
	ex.put("persons", 0);
	ex.put("companies", 0);
	
	BasicDBObject query = new BasicDBObject("shortName", projectId);
	
	DBObject p = projectRepo.getProjects().getDbCollection().findOne(query, ex);

	if (p == null) {
		getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
		return Util.generateErrorMessageRepresentation(generateRequestJson(mapper, projectId), "No project was found with the requested name.");
	}
	
	try {
		StringRepresentation resp = new StringRepresentation(p.toString());
		resp.setMediaType(MediaType.APPLICATION_JSON);
		return resp;
	} catch (Exception e) {
		e.printStackTrace();
		getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
		return Util.generateErrorMessageRepresentation(generateRequestJson(mapper, projectId), "An error occurred when converting the project to JSON: " + e.getMessage());
	}
}
 
Example 4
Source File: EntityDataController.java    From restfiddle with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/api/{projectId}/entities/{name}/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
   public @ResponseBody
   String getEntityDataById(@PathVariable("projectId") String projectId, @PathVariable("name") String entityName,
    @PathVariable("id") String entityDataId,
    @RequestHeader(value = "authToken", required = false) String authToken) {

JSONObject authRes = authService.authorize(projectId,authToken,"USER");
if(!authRes.getBoolean(SUCCESS)){
    return authRes.toString(4);
}

DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_"+entityName);

BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(entityDataId));

DBObject resultObject = dbCollection.findOne(queryObject);

if(resultObject == null){
    return "Not Found";
}

if(entityName.equals("User")){
    resultObject.removeField(PASSWORD);
}

dbRefToRelation(resultObject);
String json = resultObject.toString();

// Indentation
JSONObject jsonObject = new JSONObject(json);
return jsonObject.toString(4);
   }
 
Example 5
Source File: SubDocAccessor.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public boolean doUpdate(Query query, Update update) {
    DBObject queryDBObject = toSubDocQuery(query, true);

    DBObject elementMatch = new BasicDBObject("$elemMatch", query.getQueryObject());
    queryDBObject.put(subField, elementMatch);

    DBObject patchUpdate = toSubDocUpdate(update);
    String updateCommand = "{findAndModify:\"" + collection + "\",query:" + queryDBObject.toString()
            + ",update:" + patchUpdate.toString() + "}";
    LOG.debug("the update date mongo command is: {}", updateCommand);
    TenantContext.setIsSystemCall(false);
    CommandResult result = template.executeCommand(updateCommand);
    return result.get("value") != null;

}
 
Example 6
Source File: MongoQuery.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
@Override
public String map(DBObject dbo) {
    return dbo.toString();
}
 
Example 7
Source File: CommonG.java    From bdt with Apache License 2.0 4 votes vote down vote up
/**
 * Checks the different results of a previous query to Mongo database
 *
 * @param expectedResults A DataTable Object with all data needed for check the results. The DataTable must contains at least 2 columns:
 *                        a) A field column from the result
 *                        b) Occurrences column (Integer type)
 *                        <p>
 *                        Example:
 *                        |latitude| longitude|place     |occurrences|
 *                        |12.5    |12.7      |Valencia  |1           |
 *                        |2.5     | 2.6      |Stratio   |0           |
 *                        |12.5    |13.7      |Sevilla   |1           |
 *                        IMPORTANT: All columns must exist
 * @throws Exception exception
 */
public void resultsMustBeMongo(DataTable expectedResults) throws Exception {
    if (getMongoResults() != null) {
        //Map for cucumber expected results
        List<Map<String, Object>> resultsListExpected = new ArrayList<Map<String, Object>>();
        Map<String, Object> resultsCucumber;

        for (int e = 1; e < expectedResults.cells().size(); e++) {
            resultsCucumber = new HashMap<String, Object>();

            for (int i = 0; i < expectedResults.cells().get(0).size(); i++) {
                resultsCucumber.put(expectedResults.cells().get(0).get(i), expectedResults.cells().get(e).get(i));

            }
            resultsListExpected.add(resultsCucumber);
        }
        getLogger().debug("Expected Results: " + resultsListExpected.toString());

        //Comparisons
        int occurrencesObtained = 0;
        int iterations = 0;
        int occurrencesExpected = 0;
        String nextKey;
        for (int e = 0; e < resultsListExpected.size(); e++) {
            iterations = 0;
            occurrencesObtained = 0;
            occurrencesExpected = Integer.parseInt(resultsListExpected.get(e).get("occurrences").toString());

            String resultsListObtained = "[";
            DBCursor cursor = getMongoResults();
            while (cursor.hasNext()) {

                DBObject row = cursor.next();

                resultsListObtained = resultsListObtained + row.toString();
                if (cursor.hasNext()) {
                    resultsListObtained = ", " + resultsListObtained;
                }

                Iterator<String> it = resultsListExpected.get(0).keySet().iterator();

                while (it.hasNext()) {
                    nextKey = it.next();
                    if (!nextKey.equals("occurrences")) {
                        if (row.get(nextKey).toString().equals(resultsListExpected.get(e).get(nextKey).toString())) {
                            iterations++;
                        }
                    }

                    if (iterations == resultsListExpected.get(0).keySet().size() - 1) {
                        occurrencesObtained++;
                        iterations = 0;
                    }
                }
                iterations = 0;
                if (cursor.hasNext()) {
                    resultsListObtained = resultsListObtained + ",";
                }
            }

            resultsListObtained = resultsListObtained + "]";
            getLogger().debug("Results: " + resultsListObtained);

            assertThat(occurrencesExpected).overridingErrorMessage("In row " + e + " have been found "
                    + occurrencesObtained + " results and " + occurrencesExpected + " were expected").isEqualTo(occurrencesObtained);
        }

    } else {
        throw new Exception("You must execute a query before trying to get results");
    }
}