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

The following examples show how to use org.bson.Document#toJson() . 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: GetMongo.java    From nifi with Apache License 2.0 6 votes vote down vote up
private String buildBatch(List<Document> documents, String jsonTypeSetting, String prettyPrintSetting) throws IOException {
    StringBuilder builder = new StringBuilder();
    for (int index = 0; index < documents.size(); index++) {
        Document document = documents.get(index);
        String asJson;
        if (jsonTypeSetting.equals(JSON_TYPE_STANDARD)) {
            asJson = getObjectWriter(objectMapper, prettyPrintSetting).writeValueAsString(document);
        } else {
            asJson = document.toJson(new JsonWriterSettings(true));
        }
        builder
                .append(asJson)
                .append( (documents.size() > 1 && index + 1 < documents.size()) ? ", " : "" );
    }

    return "[" + builder.toString() + "]";
}
 
Example 2
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Resource getResource(String key, String value) throws OneM2MException {

		Document doc = this.getDocument(key, value);
		if (doc == null) {
			return null;
		}

		RESOURCE_TYPE resType = RESOURCE_TYPE.get((int) doc.get(RESTYPE_KEY));
		DaoJSONConvertor<?> jc = getJsonConvertor(resType);
		Resource res;
		try {
			res = (Resource) jc.unmarshal(doc.toJson());
			res.setUri(doc.getString(URI_KEY));
			// res.setId(doc.getString(OID_KEY));
		} catch (Exception e) {
			log.debug("Handled exception", e);
			throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR,
					"unmarshal file in ResouceDAO.getResourceWithUri:"
							+ doc.toJson());
		}
		return res;
	}
 
Example 3
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Resource getResourceWithID(String resourceID) throws OneM2MException {

		Document doc = this.getDocument(resourceID);
		
		if (doc == null) {
			return null;
		}

		RESOURCE_TYPE resType = RESOURCE_TYPE.get((int) doc.get(RESTYPE_KEY));
		DaoJSONConvertor<?> jc = getJsonConvertor(resType);
		Resource res;
		try {
			res = (Resource) jc.unmarshal(doc.toJson());
			res.setUri(doc.getString(URI_KEY));
			// res.setId(doc.getString(OID_KEY));
		} catch (Exception e) {
			log.debug("Handled exception", e);
			throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR,
					"unmarshal file in ResouceDAO.getResourceWithID:"
							+ doc.toJson());
		}
		return res;

	}
 
Example 4
Source File: MongoDb4MapMessageTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    final Logger logger = LogManager.getLogger();
    final MapMessage<?, Object> mapMessage = new MapMessage<>();
    mapMessage.with("SomeName", "SomeValue");
    mapMessage.with("SomeInt", 1);
    logger.info(mapMessage);
    //
    try (final MongoClient mongoClient = mongoDbTestRule.getMongoClient()) {
        final MongoDatabase database = mongoClient.getDatabase("testDb");
        Assert.assertNotNull(database);
        final MongoCollection<Document> collection = database.getCollection("testCollection");
        Assert.assertNotNull(collection);
        final Document first = collection.find().first();
        Assert.assertNotNull(first);
        final String firstJson = first.toJson();
        Assert.assertEquals(firstJson, "SomeValue", first.getString("SomeName"));
        Assert.assertEquals(firstJson, Integer.valueOf(1), first.getInteger("SomeInt"));
    }
}
 
Example 5
Source File: BsonToJsonLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() {
   
    String json = null;
    try (MongoClient mongoClient = new MongoClient()) {
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
        Document bson = mongoDatabase.getCollection("Books").find().first();
        json = bson.toJson(JsonWriterSettings
            .builder()
            .outputMode(JsonMode.RELAXED)
            .build());
    }
    
    String expectedJson = "{\"_id\": \"isbn\", " + 
        "\"className\": \"com.baeldung.bsontojson.Book\", " + 
        "\"title\": \"title\", " + 
        "\"author\": \"author\", " + 
        "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + 
        "\"name\": \"publisher\"}, " + 
        "\"price\": 3.95, " + 
        "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}";

    assertNotNull(json);
    
    assertEquals(expectedJson, json);
}
 
Example 6
Source File: MongoTemplateRecordConsumerTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecords()
    throws JsonParseException, JsonMappingException, IOException, AnalysisEngineProcessException {
  process();
  FindIterable<Document> find = recordsCollection.find();
  Document document = find.first();
  String json = document.toJson();
  ObjectMapper mapper = new ObjectMapper();
  MongoExtractedRecords mongoRecords = mapper.readValue(json, MongoExtractedRecords.class);
  assertEquals(
      "17e5e009b415a7c97e35f700fe9c36cc67c1b8a8457a1136e6b9eca001cd361a",
      mongoRecords.getExternalId());
  assertEquals("MongoTemplateRecordConsumer.txt", mongoRecords.getSourceUri());
  Map<String, Collection<ExtractedRecord>> records = mongoRecords.getRecords();
  checkRecords(records);
}
 
Example 7
Source File: VariableMapConverter.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Override
public Vars<?> convert(Document source) {
    try {
        String type = source.getString(Vars.JSON_TYPE_FIELD);

        if (Objects.isNull(type)) {
            source.put(Vars.JSON_TYPE_FIELD, Vars.JSON_STRING_TYPE);
            type = Vars.JSON_STRING_TYPE;
        }

        if (type.equals(Vars.JSON_STRING_TYPE)) {
            return objectMapper.readValue(source.toJson(), StringVars.class);
        }

        if (type.equals(Vars.JSON_TYPED_TYPE)) {
            return objectMapper.readValue(source.toJson(), TypedVars.class);
        }

        throw new ArgumentException("Missing type code for vars");

    } catch (IOException e) {
        throw new ArgumentException("Cannot parse mongo doc {0} to StringVars", source.toJson());
    }
}
 
Example 8
Source File: BsonToJsonLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() {

    String json = null;
    try (MongoClient mongoClient = new MongoClient()) {
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
        Document bson = mongoDatabase.getCollection("Books").find().first();
        json = bson.toJson();
    }
    
    String expectedJson = "{\"_id\": \"isbn\", " + 
        "\"className\": \"com.baeldung.bsontojson.Book\", " + 
        "\"title\": \"title\", " + 
        "\"author\": \"author\", " + 
        "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + 
        "\"name\": \"publisher\"}, " + 
        "\"price\": 3.95, " + 
        "\"publishDate\": {\"$date\": 1577898812000}}";

    assertNotNull(json);
    
    assertEquals(expectedJson, json);
}
 
Example 9
Source File: MongoNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/**
 * Convert document to note.
 */
private Note documentToNote(Document doc) throws IOException {
  // document to JSON
  String json = doc.toJson();
  // JSON to note
  return Note.fromJson(json);
}
 
Example 10
Source File: MongoHelper.java    From MongoExplorer with MIT License 5 votes vote down vote up
public static String saveDocument(String collectionName, String content) {
	Document doc = Document.parse(content);

	if (doc.containsKey("_id")) {
		Document filter = new Document("_id", doc.get("_id"));
		Database.getCollection(collectionName).findOneAndReplace(filter, doc);
	} else {
		Database.getCollection(collectionName).insertOne(doc);
	}

	return doc.toJson();
}
 
Example 11
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 12
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
private Map<String, TransformSpec> addResolvedTileSpecs(final StackId stackId,
                                                        final Document tileQuery,
                                                        final RenderParameters renderParameters) {

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);

    // EXAMPLE:   find({"z": 4050.0 , "minX": {"$lte": 239850.0} , "minY": {"$lte": 149074.0}, "maxX": {"$gte": -109.0}, "maxY": {"$gte": 370.0}}).sort({"tileId": 1})
    // INDEXES:   z_1_minY_1_minX_1_maxY_1_maxX_1_tileId_1 (z1_minX_1, z1_maxX_1, ... used for edge cases)

    // order tile specs by tileId to ensure consistent coordinate mapping
    final Document orderBy = new Document("tileId", 1);

    try (final MongoCursor<Document> cursor = tileCollection.find(tileQuery).sort(orderBy).iterator()) {
        Document document;
        TileSpec tileSpec;
        int count = 0;
        while (cursor.hasNext()) {
            if (count > 50000) {
                throw new IllegalArgumentException("query too broad, over " + count + " tiles match " + tileQuery);
            }
            document = cursor.next();
            tileSpec = TileSpec.fromJson(document.toJson());
            renderParameters.addTileSpec(tileSpec);
            count++;
        }
    }

    if (LOG.isDebugEnabled()) {
        String queryJson = tileQuery.toJson();
        if (queryJson.length() > 100) {
            queryJson = queryJson.substring(0, 95) + " ...}";
        }
        LOG.debug("addResolvedTileSpecs: found {} tile spec(s) for {}.find({}).sort({})",
                  renderParameters.numberOfTileSpecs(), MongoUtil.fullName(tileCollection),
                  queryJson, orderBy.toJson());
    }

    return resolveTransformReferencesForTiles(stackId, renderParameters.getTileSpecs());
}
 
Example 13
Source File: OldMongoNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/**
 * Convert document to note
 */
private Note documentToNote(Document doc) throws IOException {
  // document to JSON
  String json = doc.toJson();
  // JSON to note
  return Note.fromJson(json);
}
 
Example 14
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 15
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Resource getResource(String id) throws OneM2MException {

		Document doc = this.getDocument(id);
		if (doc == null) {
			return null;
		}

		log.debug(doc.toJson());
		
		RESOURCE_TYPE resType = RESOURCE_TYPE.get((int) doc.get(RESTYPE_KEY));
		String contDefinition = doc.getString(CONTAINER_DEFINITION_KEY);		// added in 2016-11-21
		//DaoJSONConvertor<?> jc = getJsonConvertor(resType);  blocked in 2016-11-21
		DaoJSONConvertor<?> jc = null;
		
		if(contDefinition != null && !contDefinition.equals("")) {
			jc = getFlexContainerJsonConvertor(contDefinition);
		} else {
			jc = getJsonConvertor(resType);
		}
		
		Resource res;
		try {
			res = (Resource) jc.unmarshal(doc.toJson());
			res.setUri(doc.getString(URI_KEY));
			// res.setId(doc.getString(OID_KEY));
		} catch (Exception e) {
			log.debug("Handled exception", e);
			throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR,
					"unmarshal file in ResouceDAO.getResourceWithUri:"
							+ doc.toJson());
		}
		return res;
	}
 
Example 16
Source File: EventReadConverter.java    From ic with MIT License 5 votes vote down vote up
/**
 * 解析并将id转换成long类型,同时支持int和long两种格式
 */
private long parseId(Document source) {
    Object id = source.get("id");
    if (id instanceof Integer) {
        return ((Integer) id).longValue();
    } else if (id instanceof Long) {
        return (long) id;
    } else {
        throw new ICException(ExceptionEnum.DATA_CONVERTER_ERROR, source.toJson());
    }
}
 
Example 17
Source File: DynamicMockRestController.java    From microcks with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/{service}/{version}/{resource}", method = RequestMethod.POST)
public ResponseEntity<String> createResource(
      @PathVariable("service") String serviceName,
      @PathVariable("version") String version,
      @PathVariable("resource") String resource,
      @RequestParam(value="delay", required=false) Long delay,
      @RequestBody(required=true) String body,
      HttpServletRequest request
) {
   log.debug("Creating a new resource '{}' for service '{}-{}'", resource, serviceName, version);
   long startTime = System.currentTimeMillis();

   serviceName = sanitizeServiceName(serviceName);

   MockContext mockContext = getMockContext(serviceName, version, "POST /" + resource);
   if (mockContext != null) {
      Document document = null;
      GenericResource genericResource = null;

      try {
         // Try parsing body payload that should be json.
         document = Document.parse(body);
         // Now create a generic resource.
         genericResource = new GenericResource();
         genericResource.setServiceId(mockContext.service.getId());
         genericResource.setPayload(document);

         genericResource = genericResourceRepository.save(genericResource);
      } catch (JsonParseException jpe) {
         // Return a 422 code : unprocessable entity.
         return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
      }

      // Append id and wait if specified before returning.
      document.append(ID_FIELD, genericResource.getId());
      waitForDelay(startTime, delay, mockContext);
      return new ResponseEntity<>(document.toJson(), HttpStatus.CREATED);
   }
   // Return a 400 code : bad request.
   return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
 
Example 18
Source File: DynamicMockRestController.java    From microcks with Apache License 2.0 4 votes vote down vote up
private String transformToResourceJSON(GenericResource genericResource) {
   Document document = genericResource.getPayload();
   document.append(ID_FIELD, genericResource.getId());
   return document.toJson();
}
 
Example 19
Source File: MongoDocumentStorage.java    From lumongo with Apache License 2.0 4 votes vote down vote up
public void getAssociatedDocuments(OutputStream outputstream, Document filter) throws IOException {
	Charset charset = Charset.forName("UTF-8");

	GridFSBucket gridFS = createGridFSConnection();
	GridFSFindIterable gridFSFiles = gridFS.find(filter);
	outputstream.write("{\n".getBytes(charset));
	outputstream.write(" \"associatedDocs\": [\n".getBytes(charset));

	boolean first = true;
	for (GridFSFile gridFSFile : gridFSFiles) {
		if (first) {
			first = false;
		}
		else {
			outputstream.write(",\n".getBytes(charset));
		}

		Document metadata = gridFSFile.getMetadata();

		String uniqueId = metadata.getString(DOCUMENT_UNIQUE_ID_KEY);
		String uniquieIdKeyValue = "  { \"uniqueId\": \"" + uniqueId + "\", ";
		outputstream.write(uniquieIdKeyValue.getBytes(charset));

		String filename = gridFSFile.getFilename();
		String filenameKeyValue = "\"filename\": \"" + filename + "\", ";
		outputstream.write(filenameKeyValue.getBytes(charset));

		Date uploadDate = gridFSFile.getUploadDate();
		String uploadDateKeyValue = "\"uploadDate\": {\"$date\":" + uploadDate.getTime() + "}";
		outputstream.write(uploadDateKeyValue.getBytes(charset));

		metadata.remove(TIMESTAMP);
		metadata.remove(COMPRESSED_FLAG);
		metadata.remove(DOCUMENT_UNIQUE_ID_KEY);
		metadata.remove(FILE_UNIQUE_ID_KEY);

		if (!metadata.isEmpty()) {
			String metaJson = metadata.toJson();
			String metaString = ", \"meta\": " + metaJson;
			outputstream.write(metaString.getBytes(charset));
		}

		outputstream.write(" }".getBytes(charset));

	}
	outputstream.write("\n ]\n}".getBytes(charset));
}
 
Example 20
Source File: MongodbManager.java    From grain with MIT License 3 votes vote down vote up
/**
 * mongodb转对象格式
 * 
 * @param document
 * @param clazz
 * @return
 */
public static <T> T documentToObject(Document document, Class<T> clazz) {
	Gson gson = new Gson();
	String objStr = document.toJson();
	T obj = gson.fromJson(objStr, clazz);
	return obj;
}