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

The following examples show how to use org.bson.Document#parse() . 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: ChangeStreamOperations.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
public static ChangeStreamOperation createChangeStreamOperation(final String changeStreamJson) {
  Document document = Document.parse(changeStreamJson);
  ChangeStreamOperation changeStreamOperation;
  switch (document.get("operationType", "unknown").toLowerCase()) {
    case "dropdatabase":
      changeStreamOperation = DROP_DATABASE;
      break;
    case "drop":
      changeStreamOperation = DROP;
      break;
    case "insert":
      changeStreamOperation =
          new Insert(document.get("documentKey", new Document()).getInteger("_id", -1));
      break;
    default:
      changeStreamOperation = new Unknown(changeStreamJson);
  }
  return changeStreamOperation;
}
 
Example 2
Source File: ExpressionsTestBase.java    From morphia with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void assertAndCheckDocShape(final String expectedString, final Expression value, final Object expectedValue) {
    Document expected = Document.parse(expectedString);
    DocumentWriter writer = new DocumentWriter();
    ((Codec) getMapper().getCodecRegistry()
                        .get(MathExpression.class))
        .encode(writer, value, EncoderContext.builder().build());
    Document actual = writer.getDocument();
    assertEquals(0, writer.getDocsLevel());
    assertEquals(0, writer.getArraysLevel());
    assertDocumentEquals(expected, actual);

    Document test = getDs().aggregate(User.class)
                           .project(Projection.of()
                                              .include("test", value))
                           .execute(Document.class)
                           .next();
    Assert.assertEquals(expectedValue, test.get("test"));
}
 
Example 3
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void create(Resource res) throws OneM2MException {
	
	Document curDoc = getDocument(URI_KEY, res.getUri());
	if (curDoc != null) {
		// added to support logic to delete expired resource
		// logic added in 2016-12-27
		String expirationTime = curDoc.getString(EXPIRETIME_KEY);
		if(expirationTime != null && Utils.checkIfExpired(expirationTime)) {
			String resUri = curDoc.getString(URI_KEY);
			this.deleteDocument(URI_KEY, resUri);
		} else {
			throw new OneM2MException(RESPONSE_STATUS.CONFLICT,
					"Resource already exist!!! :" + res.getUri());
		}
	}		

	String strJson = resourceToJson(res);
	log.debug("Res json: {} ", strJson);
	
	String currentTime = getTimeString(LocalDateTime.now());
	res.setCreationTime(currentTime);
	res.setLastModifiedTime(currentTime);

	Document doc = Document.parse(strJson);
	doc.append(ResourceDAO.URI_KEY, res.getUri());
	doc.append(ResourceDAO.CRETIME_KEY, currentTime);
	doc.append(ResourceDAO.LASTMODTIME_KEY, currentTime);

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

	collection.insertOne(doc);
	
}
 
Example 4
Source File: DocumentVisibilityAdapterTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testToDocumentVisibility_and() throws MalformedDocumentVisibilityException {
    final Document document = Document.parse(
        "{" +
            "documentVisibility : [\"A\", \"B\", \"C\"]" +
        "}"
    );
    final DocumentVisibility dv = DocumentVisibilityAdapter.toDocumentVisibility(document);
    final DocumentVisibility expected = new DocumentVisibility("A&B&C");
    assertEquals(expected, dv);
}
 
Example 5
Source File: DocumentVisibilityAdapterTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testToDocument_and() {
    final DocumentVisibility dv = new DocumentVisibility("A&B&C");
    final Document document = DocumentVisibilityAdapter.toDocument(dv);
    final Document expected = Document.parse(
        "{" +
            "documentVisibility : [[\"A\", \"B\", \"C\"]]" +
        "}"
    );
    assertEquals(expected, document);
}
 
Example 6
Source File: ContentInstanceAnncManager.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override 
public void notification(Resource parentRes, Resource reqRes, Resource orgRes, OPERATION op) throws OneM2MException {
	Document reqDoc = reqRes == null? null : Document.parse( ((ContentInstanceDAO)getDAO()).resourceToJson(reqRes));
	Document orgDoc = orgRes == null? null : Document.parse( ((ContentInstanceDAO)getDAO()).resourceToJson(orgRes));
	NotificationController.getInstance().notify(parentRes, reqDoc, reqRes, orgDoc, orgRes, op, this);
	
	// SO/SDA Interface implementation
	RestNotificationController.getInstance().notify(parentRes, reqDoc, reqRes, orgDoc, orgRes, op, this);
	RestCommandController.getInstance().processResult((ContentInstance)reqRes);
	
	RestCommandController.getInstance().processResult2((ContentInstance)reqRes);	// added by brianmoon at 2016-09-26
}
 
Example 7
Source File: PermissionStore.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public void updatePermissions(String resourceId, Permissions permissions) throws IResourceStore.ResourceStoreException {
    String jsonPermissions = serialize(permissions);
    Document permissionsDocument = Document.parse(jsonPermissions);

    permissionsDocument.put("_id", new ObjectId(resourceId));

    collection.updateOne(new Document("_id", new ObjectId(resourceId)),
            new Document("$set", permissions), new UpdateOptions().upsert(true));
}
 
Example 8
Source File: OldMongoNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/**
 * Convert note to document
 */
private Document noteToDocument(Note note) {
  // note to JSON
  String json = note.toJson();
  // JSON to document
  Document doc = Document.parse(json);
  // set object id as note id
  doc.put("_id", note.getId());
  return doc;
}
 
Example 9
Source File: DocumentVisibilityAdapterTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testToDocument_Expression() {
    final DocumentVisibility dv = new DocumentVisibility("A&B&C");
    final Document document = DocumentVisibilityAdapter.toDocument(dv.getExpression());
    final Document expected = Document.parse(
        "{" +
            "documentVisibility : [[\"A\", \"B\", \"C\"]]" +
        "}"
    );
    assertEquals(expected, document);
}
 
Example 10
Source File: Mongo.java    From baleen with Apache License 2.0 5 votes vote down vote up
private Document toBson(final Object o) throws AnalysisEngineProcessException {
  // Somewhat ridiculous approach to generating something that Mongo can save, but at least its
  // consistent with ES and the original POJO
  try {
    final String json = OBJECT_MAPPER.writeValueAsString(o);
    return Document.parse(json);
  } catch (final Exception e) {
    throw new AnalysisEngineProcessException(e);
  }
}
 
Example 11
Source File: DocumentVisibilityAdapterTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testToDocumentVisibility() throws MalformedDocumentVisibilityException {
    final Document document = Document.parse(
        "{" +
            "documentVisibility : [\"A\"]" +
        "}"
    );
    final DocumentVisibility dv = DocumentVisibilityAdapter.toDocumentVisibility(document);
    final DocumentVisibility expected = new DocumentVisibility("A");
    assertEquals(expected, dv);
}
 
Example 12
Source File: DocumentVisibilityAdapterTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testToDocumentVisibility_empty() throws MalformedDocumentVisibilityException {
    final Document document = Document.parse(
        "{" +
            "documentVisibility : []" +
        "}"
    );
    final DocumentVisibility dv = DocumentVisibilityAdapter.toDocumentVisibility(document);
    final DocumentVisibility expected = MongoDbRdfConstants.EMPTY_DV;
    assertEquals(expected, dv);
}
 
Example 13
Source File: RequestManager.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override 
public void notification(Resource parentRes, Resource reqRes, Resource orgRes, OPERATION op) throws OneM2MException {
	Document reqDoc = reqRes == null? null : Document.parse( ((RequestDAO)getDAO()).resourceToJson(reqRes));
	Document orgDoc = orgRes == null? null : Document.parse( ((RequestDAO)getDAO()).resourceToJson(orgRes));
	NotificationController.getInstance().notify(parentRes, reqDoc, reqRes, orgDoc, orgRes, op, this);
}
 
Example 14
Source File: RestSemanticController.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public boolean deleteDescriptor(String uri, String descriptor, String contType) {
	boolean isSuccess = false;
	
	try {
		
		OneM2mResponse resMessage = null;
		
		if(uri == null || uri.equals("") || descriptor == null || descriptor.equals("") || contType == null || contType.equals("") ) {
			return false;
		}
		
		String semanticEngineUri = this.semanticRestURL + "delete";
		RestSemanticCI param = new RestSemanticCI();
		param.setParamUri(uri);
		param.setParamDescriptor(descriptor);
		param.setParamContentType(contType);
		
		JSONConvertor<RestSemanticCI> cvtRcr = (JSONConvertor<RestSemanticCI>) ConvertorFactory.getJSONConvertor(RestSemanticCI.class, null);
		
		String jsonParam = cvtRcr.marshal(param);
		OneM2mRequest reqMessage = new OneM2mRequest();
		
		reqMessage.setContent(jsonParam.getBytes());
		
		reqMessage.setTo(extractToFromFullUri(semanticEngineUri));
		reqMessage.setOperation(OPERATION.CREATE);
		reqMessage.setContentType(CONTENT_TYPE.JSON);
		
		resMessage = HttpClient.getInstance().sendRequest(semanticEngineUri, reqMessage);
		
		byte[] body = resMessage.getContent();
		String resJson = new String(resMessage.getContent());
		Document resDoc = Document.parse(resJson);
		
		isSuccess = resDoc.getBoolean("ret");
		
	} catch (Exception e) {
		log.error("deleteDescriptor", e);
	}
	
	return isSuccess;
}
 
Example 15
Source File: GeoTemporalMongoDBStorageStrategyTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void serializeTest() {
    final Resource subject = VF.createIRI("foo:subj");
    final Resource context = VF.createIRI("foo:context");

    //GEO
    IRI predicate = GeoConstants.GEO_AS_WKT;
    Value object = VF.createLiteral("Point(-77.03524 38.889468)", GeoConstants.XMLSCHEMA_OGC_WKT);

    Statement statement = VF.createStatement(subject, predicate, object, context);
    RyaStatement ryaStatement = RdfToRyaConversions.convertStatement(statement);
    int expectedId = ryaStatement.getSubject().hashCode();
    Document actual = adapter.serialize(ryaStatement);
    String expectedString =
        "{ "
        + "\"_id\" : " + expectedId + ", "
        + "\"location\" : { "
          + "\"coordinates\" : [ -77.03524 , 38.889468] , "
          + "\"type\" : \"Point\""
        + "}"
      + "}";
    Document expected = Document.parse(expectedString);
    assertEqualMongo(expected, actual);

    //TIME INSTANT
    predicate = VF.createIRI("Property:event:time");
    object = VF.createLiteral("2015-12-30T12:00:00Z");
    statement = VF.createStatement(subject, predicate, object, context);
    ryaStatement = RdfToRyaConversions.convertStatement(statement);
    expectedId = ryaStatement.getSubject().hashCode();
    actual = adapter.serialize(ryaStatement);
    expectedString =
            "{"
              +"_id : " + expectedId + ", "
              +"time: {"
                + "instant : {"
                  +"\"$date\" : \"2015-12-30T12:00:00.000Z\""
                + "}"
            + "}"
          + "}";
    expected = Document.parse(expectedString);
    assertEqualMongo(expected, actual);

    //TIME INTERVAL
    predicate = VF.createIRI("Property:circa");
    object = VF.createLiteral("[1969-12-31T19:00:00-05:00,1969-12-31T19:00:01-05:00]");
    statement = VF.createStatement(subject, predicate, object, context);
    ryaStatement = RdfToRyaConversions.convertStatement(statement);
    expectedId = ryaStatement.getSubject().hashCode();
    actual = adapter.serialize(ryaStatement);
    expectedString =
            "{"
            +"_id : " + expectedId + ", "
            +"time: {"
              + "start : {"
                +"\"$date\" : \"1970-01-01T00:00:00.000Z\""
              + "},"
              + "end : {"
                +"\"$date\" : \"1970-01-01T00:00:01.000Z\""
              + "}"
          + "}"
        + "}";
    expected = Document.parse(expectedString);
    assertEqualMongo(expected, actual);
}
 
Example 16
Source File: MongoDetailsAdapterTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void mongoToRyaDetailsTest() throws MalformedRyaDetailsException {
    // Convert the Mongo object into a RyaDetails.
    final Document mongo = Document.parse(
            "{ "
                    + "instanceName : \"test\","
                    + "version : \"1\","
                    + "entityCentricDetails : true,"
                    //RYA-215            + "geoDetails : true,"
                    + "pcjDetails : {"
                    +    "enabled : true ,"
                    +    "fluoName : \"fluo\","
                    +    "pcjs : [ "
                    +       "{"
                    +          "id : \"pcj_0\","
                    +          "updateStrategy : \"BATCH\","
                    +          "lastUpdate : { $date : \"1970-01-01T00:00:00.000Z\"}"
                    +       "},"
                    +       "{"
                    +          "id : \"pcj_1\","
                    +          "updateStrategy : \"BATCH\","
                    +          "lastUpdate : { $date : \"1970-01-01T00:00:00.001Z\"}"
                    +       "}]"
                    + "},"
                    + "temporalDetails : true,"
                    + "freeTextDetails : true,"
                    + "prospectorDetails : { $date : \"1970-01-01T00:00:00.000Z\"},"
                    + "joinSelectivitiyDetails : { $date : \"1970-01-01T00:00:00.001Z\"},"
                    + "ryaStreamsDetails : { hostname : \"localhost\" , port : 6}"
                    + "}"
            );

    final RyaDetails actual = MongoDetailsAdapter.toRyaDetails(mongo);

    // Ensure it matches the expected object.
    final RyaDetails expected = RyaDetails.builder()
            .setRyaInstanceName("test")
            .setRyaVersion("1")
            .setEntityCentricIndexDetails(new EntityCentricIndexDetails(true))
            //RYA-215            .setGeoIndexDetails(new GeoIndexDetails(true))
            .setPCJIndexDetails(
                    PCJIndexDetails.builder()
                    .setEnabled(true)
                    .addPCJDetails(
                            PCJDetails.builder()
                            .setId("pcj_0")
                            .setUpdateStrategy(PCJUpdateStrategy.BATCH)
                            .setLastUpdateTime(new Date(0L)))
                    .addPCJDetails(
                            PCJDetails.builder()
                            .setId("pcj_1")
                            .setUpdateStrategy(PCJUpdateStrategy.BATCH)
                            .setLastUpdateTime(new Date(1L))))
            .setTemporalIndexDetails(new TemporalIndexDetails(true))
            .setFreeTextDetails(new FreeTextIndexDetails(true))
            .setProspectorDetails(new ProspectorDetails(Optional.<Date>fromNullable(new Date(0L))))
            .setJoinSelectivityDetails(new JoinSelectivityDetails(Optional.<Date>fromNullable(new Date(1L))))
            .setRyaStreamsDetails(new RyaStreamsDetails("localhost", 6))
            .build();

    assertEquals(expected, actual);
}
 
Example 17
Source File: GroupAnncManager.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override 
public void notification(Resource parentRes, Resource reqRes, Resource orgRes, OPERATION op) throws OneM2MException {
	Document reqDoc = reqRes == null? null : Document.parse( ((GroupAnncDAO)getDAO()).resourceToJson(reqRes));
	Document orgDoc = orgRes == null? null : Document.parse( ((GroupAnncDAO)getDAO()).resourceToJson(orgRes));
	NotificationController.getInstance().notify(parentRes, reqDoc, reqRes, orgDoc, orgRes, op, this);
}
 
Example 18
Source File: RemoteCSEAnncManager.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override 
public void notification(Resource parentRes, Resource reqRes, Resource orgRes, OPERATION op) throws OneM2MException {
	Document reqDoc = reqRes == null? null : Document.parse( ((RemoteCSEAnncDAO)getDAO()).resourceToJson(reqRes));
	Document orgDoc = orgRes == null? null : Document.parse( ((RemoteCSEAnncDAO)getDAO()).resourceToJson(orgRes));
	NotificationController.getInstance().notify(parentRes, reqDoc, reqRes, orgDoc, orgRes, op, this);
}
 
Example 19
Source File: RestSemanticController.java    From SI with BSD 2-Clause "Simplified" License 3 votes vote down vote up
public boolean validate(String strRdf) {
	boolean isValidate = false;
	
	try {
		
		OneM2mResponse resMessage = null;
		
		String semanticEngineUri = this.semanticRestURL + "validate";
		RestSemanticCI param = new RestSemanticCI();
		param.setParamDescriptor(strRdf);
		
		JSONConvertor<RestSemanticCI> cvtRcr = (JSONConvertor<RestSemanticCI>) ConvertorFactory.getJSONConvertor(RestSemanticCI.class, null);
		
		String jsonParam = cvtRcr.marshal(param);
		OneM2mRequest reqMessage = new OneM2mRequest();
		
		reqMessage.setContent(jsonParam.getBytes());
		
		reqMessage.setTo(extractToFromFullUri(semanticEngineUri));
		reqMessage.setOperation(OPERATION.CREATE);
		reqMessage.setContentType(CONTENT_TYPE.JSON);
		
		resMessage = HttpClient.getInstance().sendRequest(semanticEngineUri, reqMessage);
		
		byte[] body = resMessage.getContent();
		String resJson = new String(resMessage.getContent());
		Document resDoc = Document.parse(resJson);
		
		isValidate = resDoc.getBoolean("ret");
		
	} catch (Exception e) {
		log.error("processSemanticOperation", e);
	}
	
	return isValidate;
	
}
 
Example 20
Source File: MongoTemplateRecordConsumer.java    From baleen with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a mongo document pojo for serialisation.
 *
 * @param mongoRecords the mongo records
 * @return the document
 * @throws JsonProcessingException the json processing exception
 */
private Document createMongoDocument(MongoExtractedRecords mongoRecords)
    throws JsonProcessingException {
  String json = objectMapper.writeValueAsString(mongoRecords);
  return Document.parse(json);
}