Java Code Examples for org.bson.BsonDocument#getDocument()

The following examples show how to use org.bson.BsonDocument#getDocument() . 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: RdbmsHandler.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
static BsonDocument generateUpsertOrReplaceDoc(
    final BsonDocument keyDoc, final BsonDocument valueDoc, final BsonDocument filterDoc) {

  if (!valueDoc.containsKey(JSON_DOC_AFTER_FIELD)
      || valueDoc.get(JSON_DOC_AFTER_FIELD).isNull()
      || !valueDoc.get(JSON_DOC_AFTER_FIELD).isDocument()
      || valueDoc.getDocument(JSON_DOC_AFTER_FIELD).isEmpty()) {
    throw new DataException(
        "Error: valueDoc must contain non-empty 'after' field"
            + " of type document for insert/update operation");
  }

  BsonDocument upsertDoc = new BsonDocument();
  if (filterDoc.containsKey(ID_FIELD)) {
    upsertDoc.put(ID_FIELD, filterDoc.get(ID_FIELD));
  }

  BsonDocument afterDoc = valueDoc.getDocument(JSON_DOC_AFTER_FIELD);
  for (String f : afterDoc.keySet()) {
    if (!keyDoc.containsKey(f)) {
      upsertDoc.put(f, afterDoc.get(f));
    }
  }
  return upsertDoc;
}
 
Example 2
Source File: ReplaceOneBusinessKeyStrategy.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public WriteModel<BsonDocument> createWriteModel(final SinkDocument document) {
  BsonDocument vd =
      document
          .getValueDoc()
          .orElseThrow(
              () ->
                  new DataException(
                      "Error: cannot build the WriteModel since the value document was missing unexpectedly"));

  try {
    BsonDocument businessKey = vd.getDocument(ID_FIELD);
    vd.remove(ID_FIELD);
    return new ReplaceOneModel<>(businessKey, vd, REPLACE_OPTIONS);
  } catch (BSONException e) {
    throw new DataException(
        "Error: cannot build the WriteModel since the value document does not contain an _id field of"
            + " type BsonDocument which holds the business key fields");
  }
}
 
Example 3
Source File: RdbmsHandler.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
protected static BsonDocument generateFilterDoc(BsonDocument keyDoc, BsonDocument valueDoc, OperationType opType) {
    if (keyDoc.keySet().isEmpty()) {
        if (opType.equals(OperationType.CREATE) || opType.equals(OperationType.READ)) {
            //create: no PK info in keyDoc -> generate ObjectId
            return new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonObjectId());
        }
        //update or delete: no PK info in keyDoc -> take everything in 'before' field
        try {
            BsonDocument filter = valueDoc.getDocument(JSON_DOC_BEFORE_FIELD);
            if (filter.isEmpty())
                throw new BsonInvalidOperationException("value doc before field is empty");
            return filter;
        } catch(BsonInvalidOperationException exc) {
            throw new DataException("error: value doc 'before' field is empty or has invalid type" +
                    " for update/delete operation which seems severely wrong -> defensive actions taken!",exc);
        }
    }
    //build filter document composed of all PK columns
    BsonDocument pk = new BsonDocument();
    for (String f : keyDoc.keySet()) {
        pk.put(f,keyDoc.get(f));
    }
    return new BsonDocument(DBCollection.ID_FIELD_NAME,pk);
}
 
Example 4
Source File: RdbmsHandler.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
protected static BsonDocument generateUpsertOrReplaceDoc(BsonDocument keyDoc, BsonDocument valueDoc, BsonDocument filterDoc) {

        if (!valueDoc.containsKey(JSON_DOC_AFTER_FIELD)
                || valueDoc.get(JSON_DOC_AFTER_FIELD).isNull()
                || !valueDoc.get(JSON_DOC_AFTER_FIELD).isDocument()
                || valueDoc.getDocument(JSON_DOC_AFTER_FIELD).isEmpty()) {
            throw new DataException("error: valueDoc must contain non-empty 'after' field" +
                    " of type document for insert/update operation");
        }

        BsonDocument upsertDoc = new BsonDocument();
        if(filterDoc.containsKey(DBCollection.ID_FIELD_NAME)) {
            upsertDoc.put(DBCollection.ID_FIELD_NAME,filterDoc.get(DBCollection.ID_FIELD_NAME));
        }

        BsonDocument afterDoc = valueDoc.getDocument(JSON_DOC_AFTER_FIELD);
        for (String f : afterDoc.keySet()) {
            if (!keyDoc.containsKey(f)) {
                upsertDoc.put(f,afterDoc.get(f));
            }
        }
        return upsertDoc;
    }
 
Example 5
Source File: SubscriptionType.java    From epcis with Apache License 2.0 6 votes vote down vote up
public SubscriptionType(BsonDocument doc) {

		if (doc.containsKey("subscriptionID")) {
			this.subscriptionID = doc.getString("subscriptionID").getValue();
		}
		if (doc.containsKey("dest")) {
			this.dest = doc.getString("dest").getValue();
		}
		if (doc.containsKey("schedule")) {
			this.schedule = doc.getString("schedule").getValue();
		}
		if (doc.containsKey("trigger")) {
			this.trigger = doc.getString("trigger").getValue();
		}
		if (doc.containsKey("initialRecordTime")) {
			this.initialRecordTime = doc.getString("initialRecordTime").getValue();
		}
		if (doc.containsKey("reportIfEmpty")) {
			this.reportIfEmpty = doc.getBoolean("reportIfEmpty").getValue();
		}
		if (doc.containsKey("pollParameters")) {
			this.pollParameters = new PollParameters(doc.getDocument("pollParameters"));
		}
	}
 
Example 6
Source File: SubscriptionType.java    From epcis with Apache License 2.0 6 votes vote down vote up
public SubscriptionType(BsonDocument doc) {

		if (doc.containsKey("subscriptionID")) {
			this.subscriptionID = doc.getString("subscriptionID").getValue();
		}
		if (doc.containsKey("dest")) {
			this.dest = doc.getString("dest").getValue();
		}
		if (doc.containsKey("schedule")) {
			this.schedule = doc.getString("schedule").getValue();
		}
		if (doc.containsKey("trigger")) {
			this.trigger = doc.getString("trigger").getValue();
		}
		if (doc.containsKey("initialRecordTime")) {
			this.initialRecordTime = doc.getString("initialRecordTime").getValue();
		}
		if (doc.containsKey("reportIfEmpty")) {
			this.reportIfEmpty = doc.getBoolean("reportIfEmpty").getValue();
		}
		if (doc.containsKey("pollParameters")) {
			this.pollParameters = new PollParameters(doc.getDocument("pollParameters"));
		}
	}
 
Example 7
Source File: RecordToBson.java    From octarine with Apache License 2.0 5 votes vote down vote up
@Test public void
convert_record_with_sub_record_to_bson() {
    Record person = Record.of(
            Person.name.of("Dominic"),
            Person.age.of(39),
            Person.address.of(Address.addressLines.of(ADDRESS_LINES)));

    BsonRecordSerialiser addressSerialiser = BsonRecordSerialiser.builder()
            .writeList(Address.addressLines, BsonSerialisers.toString)
            .get();

    BsonRecordSerialiser serializer = BsonRecordSerialiser.builder()
            .writeString(Person.name)
            .writeInteger(Person.age)
            .write(Person.address, addressSerialiser)
            .get();

    BsonDocument doc = (BsonDocument) serializer.apply(person);
    assertEquals("Invalid name", "Dominic", doc.getString("name").getValue());
    assertEquals("invalid age", 39, doc.getInt32("age").getValue());
    BsonDocument bsonAddress = doc.getDocument("address");
    assertNotNull("address was null", bsonAddress);
    BsonArray bsonLines = bsonAddress.getArray("addressLines");
    assertNotNull("addressLines was null", bsonLines);
    List<String> bsonList = bsonLines.getValues().stream().map(v -> ((BsonString) v).getValue()).collect(Collectors.toList());
    assertEquals("Address contents don't match", ADDRESS_LINES, bsonList);
}
 
Example 8
Source File: RdbmsHandler.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
static BsonDocument generateFilterDoc(
    final BsonDocument keyDoc, final BsonDocument valueDoc, final OperationType opType) {
  if (keyDoc.keySet().isEmpty()) {
    if (opType.equals(OperationType.CREATE) || opType.equals(OperationType.READ)) {
      // create: no PK info in keyDoc -> generate ObjectId
      return new BsonDocument(ID_FIELD, new BsonObjectId());
    }
    // update or delete: no PK info in keyDoc -> take everything in 'before' field
    try {
      BsonDocument filter = valueDoc.getDocument(JSON_DOC_BEFORE_FIELD);
      if (filter.isEmpty()) {
        throw new BsonInvalidOperationException("value doc before field is empty");
      }
      return filter;
    } catch (BsonInvalidOperationException exc) {
      throw new DataException(
          "Error: value doc 'before' field is empty or has invalid type"
              + " for update/delete operation which seems severely wrong -> defensive actions taken!",
          exc);
    }
  }
  // build filter document composed of all PK columns
  BsonDocument pk = new BsonDocument();
  for (String f : keyDoc.keySet()) {
    pk.put(f, keyDoc.get(f));
  }
  return new BsonDocument(ID_FIELD, pk);
}
 
Example 9
Source File: MongoReaderUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
static EPCISEventExtensionType putEPCISEventExtensionType(BsonDocument dbObject, int zone) {
	EPCISEventExtensionType eeet = new EPCISEventExtensionType();
	if (dbObject.get("eventID") != null) {
		eeet.setEventID(dbObject.getString("eventID").getValue());
	} else {
		if (dbObject.containsKey("_id")) {
			eeet.setEventID(dbObject.getString("_id").getValue());
		}
	}
	if (dbObject.get("errorDeclaration") != null) {
		ErrorDeclarationType edt = new ErrorDeclarationType();
		BsonDocument error = dbObject.getDocument("errorDeclaration");
		if (error.containsKey("declarationTime")) {
			edt.setDeclarationTime(getXMLGregorianCalendar(error.getDateTime("declarationTime")));
		}
		if (error.containsKey("reason")) {
			edt.setReason(error.getString("reason").getValue());
		}
		if (error.containsKey("correctiveEventIDs")) {
			BsonArray correctiveEventIDs = error.getArray("correctiveEventIDs");
			List<String> correctiveIDs = new ArrayList<String>();
			Iterator<BsonValue> cIDIterator = correctiveEventIDs.iterator();
			while (cIDIterator.hasNext()) {
				String cID = cIDIterator.next().asString().getValue();
				correctiveIDs.add(cID);
			}
			if (correctiveIDs.size() != 0) {
				CorrectiveEventIDsType ceit = new CorrectiveEventIDsType();
				ceit.setCorrectiveEventID(correctiveIDs);
				edt.setCorrectiveEventIDs(ceit);
			}
		}
		if (error.containsKey("any")) {
			edt.setAny(putAny(error.getDocument("any"), null));
		}
		eeet.setErrorDeclaration(edt);
	}
	return eeet;
}
 
Example 10
Source File: MongoReaderUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
static EPCISEventExtensionType putEPCISEventExtensionType(BsonDocument dbObject, int zone) {
	EPCISEventExtensionType eeet = new EPCISEventExtensionType();
	if (dbObject.get("eventID") != null) {
		eeet.setEventID(dbObject.getString("eventID").getValue());
	} else {
		if (dbObject.containsKey("_id")) {
			eeet.setEventID(dbObject.getObjectId("_id").getValue().toHexString());
		}
	}
	if (dbObject.get("errorDeclaration") != null) {
		ErrorDeclarationType edt = new ErrorDeclarationType();
		BsonDocument error = dbObject.getDocument("errorDeclaration");
		if (error.containsKey("declarationTime")) {
			edt.setDeclarationTime(getXMLGregorianCalendar(error.getDateTime("declarationTime")));
		}
		if (error.containsKey("reason")) {
			edt.setReason(error.getString("reason").getValue());
		}
		if (error.containsKey("correctiveEventIDs")) {
			BsonArray correctiveEventIDs = error.getArray("correctiveEventIDs");
			List<String> correctiveIDs = new ArrayList<String>();
			Iterator<BsonValue> cIDIterator = correctiveEventIDs.iterator();
			while (cIDIterator.hasNext()) {
				String cID = cIDIterator.next().asString().getValue();
				correctiveIDs.add(cID);
			}
			if (correctiveIDs.size() != 0) {
				CorrectiveEventIDsType ceit = new CorrectiveEventIDsType();
				ceit.setCorrectiveEventID(correctiveIDs);
				edt.setCorrectiveEventIDs(ceit);
			}
		}
		if (error.containsKey("any")) {
			edt.setAny(putAny(error.getDocument("any"), null));
		}
		eeet.setErrorDeclaration(edt);
	}
	return eeet;
}
 
Example 11
Source File: UpdateDescription.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an update description BSON document from a MongoDB Change Event into an
 * UpdateDescription object.
 *
 * @param document the
 * @return the converted UpdateDescription
 */
public static UpdateDescription fromBsonDocument(final BsonDocument document) {
  keyPresent(Fields.UPDATED_FIELDS_FIELD, document);
  keyPresent(Fields.REMOVED_FIELDS_FIELD, document);

  final BsonArray removedFieldsArr =
      document.getArray(Fields.REMOVED_FIELDS_FIELD);
  final Set<String> removedFields = new HashSet<>(removedFieldsArr.size());
  for (final BsonValue field : removedFieldsArr) {
    removedFields.add(field.asString().getValue());
  }

  return new UpdateDescription(document.getDocument(Fields.UPDATED_FIELDS_FIELD), removedFields);
}
 
Example 12
Source File: DocumentVersionInfo.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the version document of the given document, if any; returns null otherwise.
 * @param document the document to get the version from.
 * @return the version of the given document, if any; returns null otherwise.
 */
static BsonDocument getDocumentVersionDoc(final BsonDocument document) {
  if (document == null || !document.containsKey(DOCUMENT_VERSION_FIELD)) {
    return null;
  }
  return document.getDocument(DOCUMENT_VERSION_FIELD, null);
}
 
Example 13
Source File: UpdateOneBusinessKeyTimestampStrategy.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Override
public WriteModel<BsonDocument> createWriteModel(final SinkDocument document) {
  BsonDocument vd =
      document
          .getValueDoc()
          .orElseThrow(
              () ->
                  new DataException(
                      "Error: cannot build the WriteModel since the value document was missing unexpectedly"));

  BsonDateTime dateTime = new BsonDateTime(Instant.now().toEpochMilli());

  try {
    BsonDocument businessKey = vd.getDocument(ID_FIELD);
    vd.remove(ID_FIELD);

    return new UpdateOneModel<>(
        businessKey,
        new BsonDocument("$set", vd.append(FIELD_NAME_MODIFIED_TS, dateTime))
            .append("$setOnInsert", new BsonDocument(FIELD_NAME_INSERTED_TS, dateTime)),
        UPDATE_OPTIONS);

  } catch (BSONException e) {
    throw new DataException(
        "Error: cannot build the WriteModel since the value document does not contain an _id field of"
            + " type BsonDocument which holds the business key fields");
  }
}
 
Example 14
Source File: MongoReaderUtil.java    From epcis with Apache License 2.0 4 votes vote down vote up
static EPCISEventExtensionType putEPCISExtension(EPCISEventExtensionType object, BsonDocument extension) {
	/*
	 * Extension of extension may be deprecated if (extension.get("any") !=
	 * null) { BsonDocument anyObject = extension.getDocument("any"); // Get
	 * Namespaces Iterator<String> anyKeysIterN =
	 * anyObject.keySet().iterator(); Map<String, String> nsMap = new
	 * HashMap<String, String>(); while (anyKeysIterN.hasNext()) { String
	 * anyKeyN = anyKeysIterN.next(); String valueN =
	 * anyObject.getString(anyKeyN).getValue(); if (anyKeyN.startsWith("@"))
	 * { nsMap.put(anyKeyN.substring(1, anyKeyN.length()), valueN); } } //
	 * Process Any Iterator<String> anyKeysIter =
	 * anyObject.keySet().iterator(); List<Object> elementList = new
	 * ArrayList<Object>(); while (anyKeysIter.hasNext()) { String anyKey =
	 * anyKeysIter.next(); if (anyKey.startsWith("@")) continue; String
	 * value = anyObject.get(anyKey).toString(); // Get Namespace String[]
	 * anyKeyCheck = anyKey.split(":"); String namespace = null; String
	 * namespaceURI = null; if (anyKeyCheck.length == 2) { namespace =
	 * anyKeyCheck[0]; namespaceURI = nsMap.get(namespace).toString(); } if
	 * (anyKey != null && value != null) { DocumentBuilderFactory dbf =
	 * DocumentBuilderFactory.newInstance(); DocumentBuilder builder =
	 * dbf.newDocumentBuilder(); Document doc = builder.newDocument();
	 * 
	 * Node node = doc.createElement("value"); node.setTextContent(value);
	 * Element element = doc.createElement(anyKey); if (namespace != null) {
	 * element.setAttribute("xmlns:" + namespace, namespaceURI); }
	 * element.appendChild(node); elementList.add(element); } }
	 * object.setAny(elementList); }
	 */
	if (extension.get("otherAttributes") != null) {
		Map<QName, String> otherAttributes = new HashMap<QName, String>();
		BsonDocument otherAttributeObject = extension.getDocument("otherAttributes");
		Iterator<String> otherKeysIter = otherAttributeObject.keySet().iterator();
		while (otherKeysIter.hasNext()) {
			String anyKey = otherKeysIter.next();
			String value = otherAttributeObject.getString(anyKey).getValue();
			otherAttributes.put(new QName("", anyKey), value);
		}
		object.setOtherAttributes(otherAttributes);
	}
	return object;
}
 
Example 15
Source File: CoreDocumentSynchronizationConfig.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
static CoreDocumentSynchronizationConfig fromBsonDocument(final BsonDocument document) {
  keyPresent(ConfigCodec.Fields.DOCUMENT_ID_FIELD, document);
  keyPresent(ConfigCodec.Fields.NAMESPACE_FIELD, document);
  keyPresent(ConfigCodec.Fields.SCHEMA_VERSION_FIELD, document);
  keyPresent(ConfigCodec.Fields.LAST_RESOLUTION_FIELD, document);
  keyPresent(ConfigCodec.Fields.IS_STALE, document);
  keyPresent(ConfigCodec.Fields.IS_PAUSED, document);

  final int schemaVersion =
      document.getNumber(ConfigCodec.Fields.SCHEMA_VERSION_FIELD).intValue();
  if (schemaVersion != 1) {
    throw new IllegalStateException(
        String.format(
            "unexpected schema version '%d' for %s",
            schemaVersion,
            CoreDocumentSynchronizationConfig.class.getSimpleName()));
  }

  final MongoNamespace namespace =
      new MongoNamespace(document.getString(ConfigCodec.Fields.NAMESPACE_FIELD).getValue());

  final BsonDocument lastVersion;
  if (document.containsKey(ConfigCodec.Fields.LAST_KNOWN_REMOTE_VERSION_FIELD)) {
    lastVersion = document.getDocument(ConfigCodec.Fields.LAST_KNOWN_REMOTE_VERSION_FIELD);
  } else {
    lastVersion = null;
  }

  final ChangeEvent<BsonDocument> lastUncommittedChangeEvent;
  if (document.containsKey(ConfigCodec.Fields.LAST_UNCOMMITTED_CHANGE_EVENT)) {
    final BsonBinary eventBin =
        document.getBinary(ConfigCodec.Fields.LAST_UNCOMMITTED_CHANGE_EVENT);
    final BsonReader innerReader = new BsonBinaryReader(ByteBuffer.wrap(eventBin.getData()));
    lastUncommittedChangeEvent = ResultDecoders.changeEventDecoder(BSON_DOCUMENT_CODEC)
        .decode(innerReader, DecoderContext.builder().build());
  } else {
    lastUncommittedChangeEvent = null;
  }

  return new CoreDocumentSynchronizationConfig(
      null,
      namespace,
      document.get(ConfigCodec.Fields.DOCUMENT_ID_FIELD),
      lastUncommittedChangeEvent,
      document.getNumber(ConfigCodec.Fields.LAST_RESOLUTION_FIELD).longValue(),
      lastVersion,
      new ReentrantReadWriteLock(),
      document.getBoolean(ConfigCodec.Fields.IS_STALE).getValue(),
      document.getBoolean(ConfigCodec.Fields.IS_PAUSED, new BsonBoolean(false)).getValue(),
      document.getInt64(ConfigCodec.Fields.LAST_KNOWN_HASH_FIELD, new BsonInt64(0))
        .getValue());
}
 
Example 16
Source File: ChangeEvent.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Deserializes a {@link BsonDocument} into an instance of change event.
 * @param document the serialized document
 * @return the deserialized change event
 */
public static ChangeEvent fromBsonDocument(final BsonDocument document) {
  keyPresent(Fields.ID_FIELD, document);
  keyPresent(Fields.OPERATION_TYPE_FIELD, document);
  keyPresent(Fields.NS_FIELD, document);
  keyPresent(Fields.DOCUMENT_KEY_FIELD, document);

  final BsonDocument nsDoc = document.getDocument(Fields.NS_FIELD);

  final UpdateDescription updateDescription;
  if (document.containsKey(Fields.UPDATE_DESCRIPTION_FIELD)) {
    updateDescription = UpdateDescription.fromBsonDocument(
        document.getDocument(Fields.UPDATE_DESCRIPTION_FIELD)
    );
  } else {
    updateDescription = null;
  }

  final BsonDocument fullDocument;
  if (document.containsKey(Fields.FULL_DOCUMENT_FIELD)) {
    final BsonValue fdVal = document.get(Fields.FULL_DOCUMENT_FIELD);
    if (fdVal.isDocument()) {
      fullDocument = fdVal.asDocument();
    } else {
      fullDocument = null;
    }
  } else {
    fullDocument = null;
  }

  return new ChangeEvent<>(
      document.getDocument(Fields.ID_FIELD),
      OperationType.fromRemote(document.getString(Fields.OPERATION_TYPE_FIELD).getValue()),
      fullDocument,
      new MongoNamespace(
          nsDoc.getString(Fields.NS_DB_FIELD).getValue(),
          nsDoc.getString(Fields.NS_COLL_FIELD).getValue()),
      document.getDocument(Fields.DOCUMENT_KEY_FIELD),
      updateDescription,
      document.getBoolean(Fields.WRITE_PENDING_FIELD, BsonBoolean.FALSE).getValue());
}
 
Example 17
Source File: MongoReaderUtil.java    From epcis with Apache License 2.0 4 votes vote down vote up
static EPCISEventExtensionType putEPCISExtension(EPCISEventExtensionType object, BsonDocument extension) {
	/*
	 * Extension of extension may be deprecated if (extension.get("any") !=
	 * null) { BsonDocument anyObject = extension.getDocument("any"); // Get
	 * Namespaces Iterator<String> anyKeysIterN =
	 * anyObject.keySet().iterator(); Map<String, String> nsMap = new
	 * HashMap<String, String>(); while (anyKeysIterN.hasNext()) { String
	 * anyKeyN = anyKeysIterN.next(); String valueN =
	 * anyObject.getString(anyKeyN).getValue(); if (anyKeyN.startsWith("@"))
	 * { nsMap.put(anyKeyN.substring(1, anyKeyN.length()), valueN); } } //
	 * Process Any Iterator<String> anyKeysIter =
	 * anyObject.keySet().iterator(); List<Object> elementList = new
	 * ArrayList<Object>(); while (anyKeysIter.hasNext()) { String anyKey =
	 * anyKeysIter.next(); if (anyKey.startsWith("@")) continue; String
	 * value = anyObject.get(anyKey).toString(); // Get Namespace String[]
	 * anyKeyCheck = anyKey.split(":"); String namespace = null; String
	 * namespaceURI = null; if (anyKeyCheck.length == 2) { namespace =
	 * anyKeyCheck[0]; namespaceURI = nsMap.get(namespace).toString(); } if
	 * (anyKey != null && value != null) { DocumentBuilderFactory dbf =
	 * DocumentBuilderFactory.newInstance(); DocumentBuilder builder =
	 * dbf.newDocumentBuilder(); Document doc = builder.newDocument();
	 * 
	 * Node node = doc.createElement("value"); node.setTextContent(value);
	 * Element element = doc.createElement(anyKey); if (namespace != null) {
	 * element.setAttribute("xmlns:" + namespace, namespaceURI); }
	 * element.appendChild(node); elementList.add(element); } }
	 * object.setAny(elementList); }
	 */
	if (extension.get("otherAttributes") != null) {
		Map<QName, String> otherAttributes = new HashMap<QName, String>();
		BsonDocument otherAttributeObject = extension.getDocument("otherAttributes");
		Iterator<String> otherKeysIter = otherAttributeObject.keySet().iterator();
		while (otherKeysIter.hasNext()) {
			String anyKey = otherKeysIter.next();
			String value = otherAttributeObject.getString(anyKey).getValue();
			otherAttributes.put(new QName("", anyKey), value);
		}
		object.setOtherAttributes(otherAttributes);
	}
	return object;
}
 
Example 18
Source File: CompactChangeEvent.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Deserializes a {@link BsonDocument} into an instance of change event.
 * @param document the serialized document
 * @return the deserialized change event
 */
public static CompactChangeEvent fromBsonDocument(final BsonDocument document) {
  keyPresent(Fields.OPERATION_TYPE_FIELD, document);
  keyPresent(Fields.DOCUMENT_KEY_FIELD, document);

  final BsonDocument fullDocument;
  if (document.containsKey(Fields.FULL_DOCUMENT_FIELD)) {
    final BsonValue fdVal = document.get(Fields.FULL_DOCUMENT_FIELD);
    if (fdVal.isDocument()) {
      fullDocument = fdVal.asDocument();
    } else {
      fullDocument = null;
    }
  } else {
    fullDocument = null;
  }

  final UpdateDescription updateDescription;
  if (document.containsKey(Fields.UPDATE_DESCRIPTION_FIELD)) {
    updateDescription = UpdateDescription.fromBsonDocument(
        document.getDocument(Fields.UPDATE_DESCRIPTION_FIELD)
    );
  } else {
    updateDescription = null;
  }

  final DocumentVersionInfo.Version stitchDocumentVersion;
  if (document.containsKey(Fields.STITCH_DOCUMENT_VERSION_FIELD)) {
    stitchDocumentVersion = DocumentVersionInfo.Version
        .fromBsonDocument(document.getDocument(Fields.STITCH_DOCUMENT_VERSION_FIELD));
  } else {
    stitchDocumentVersion = null;
  }

  final Long stitchDocumentHash;
  if (document.containsKey(Fields.STITCH_DOCUMENT_HASH_FIELD)) {
    stitchDocumentHash = document.getInt64(
        Fields.STITCH_DOCUMENT_HASH_FIELD
    ).getValue();
  } else {
    stitchDocumentHash = null;
  }

  return new CompactChangeEvent<>(
      OperationType.fromRemote(document.getString(Fields.OPERATION_TYPE_FIELD).getValue()),
      fullDocument,
      document.getDocument(Fields.DOCUMENT_KEY_FIELD),
      updateDescription,
      stitchDocumentVersion,
      stitchDocumentHash,
      document.getBoolean(Fields.WRITE_PENDING_FIELD, BsonBoolean.FALSE).getValue());
}