Deserializes a {@link BsonDocument} into an instance of change event.
@param document the serialized document
@return the deserialized change event
178753
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());
  }
771030
public Response update(String id, Object document) {
        Misc.checkNotNullOrEmpty(id, "id");
        Misc.checkNotNull(document, "Document");

        // Get the latest rev, will throw if doc doesn't exist
        getDocumentRev(id);

        return putUpdate(id, document);
    }
176214
@Override
  public BsonDocument toBsonDocument() {
    final BsonDocument asDoc = new BsonDocument();
    asDoc.put(Fields.ID_FIELD, id);

    asDoc.put(Fields.OPERATION_TYPE_FIELD, new BsonString(getOperationType().toRemote()));

    final BsonDocument nsDoc = new BsonDocument();
    nsDoc.put(Fields.NS_DB_FIELD, new BsonString(ns.getDatabaseName()));
    nsDoc.put(Fields.NS_COLL_FIELD, new BsonString(getNamespace().getCollectionName()));
    asDoc.put(Fields.NS_FIELD, nsDoc);

    asDoc.put(Fields.DOCUMENT_KEY_FIELD, getDocumentKey());

    if (getFullDocument() != null && (getFullDocument() instanceof BsonValue)
        && ((BsonValue) getFullDocument()).isDocument()) {
      asDoc.put(Fields.FULL_DOCUMENT_FIELD, (BsonValue) getFullDocument());
    }

    if (getUpdateDescription() != null) {
      asDoc.put(Fields.UPDATE_DESCRIPTION_FIELD, getUpdateDescription().toBsonDocument());
    }

    asDoc.put(Fields.WRITE_PENDING_FIELD, new BsonBoolean(hasUncommittedWrites()));
    return asDoc;
  }
842299
public static CSLItemData convert(String documentId, Map<String, Object> document) {
		//convert citation id
		String id = (String)document.get(FIELD_CITATION_KEY);
		if (id == null) {
			id = documentId;
		}
		
		//convert type
		String mtype = strOrNull(document.get(FIELD_TYPE));
		CSLType type = toType(mtype);
		
		CSLItemDataBuilder builder = new CSLItemDataBuilder().id(id).type(type);
		
		//convert authors
		if (document.containsKey(FIELD_AUTHORS)) {
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> al = (List<Map<String, Object>>)document.get(FIELD_AUTHORS);
			builder.author(toAuthors(al));
		}
		
		//convert editors
		if (document.containsKey(FIELD_EDITORS)) {
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> el = (List<Map<String, Object>>)document.get(FIELD_EDITORS);
			CSLName[] editors = toAuthors(el);
			builder.editor(editors);
			builder.collectionEditor(editors);
			builder.containerAuthor(editors);
		}
		
		if (document.containsKey(FIELD_SERIES_EDITOR)) {
			String seriesEditor = strOrNull(document.get(FIELD_SERIES_EDITOR));
			if (seriesEditor != null) {
				CSLName[] sen = NameParser.parse(seriesEditor);
				builder.collectionEditor(sen);
				builder.containerAuthor(sen);
			}
		}
		
		//convert translators
		if (document.containsKey(FIELD_TRANSLATORS)) {
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> tl = (List<Map<String, Object>>)document.get(FIELD_TRANSLATORS);
			builder.translator(toAuthors(tl));
		}
		
		//convert issue date
		if (document.containsKey(FIELD_YEAR)) {
			CSLDateBuilder db = new CSLDateBuilder();
			int year = Integer.parseInt(document.get(FIELD_YEAR).toString());
			if (document.containsKey(FIELD_MONTH)) {
				int month = Integer.parseInt(document.get(FIELD_MONTH).toString());
				if (document.containsKey(FIELD_DAY)) {
					int day = Integer.parseInt(document.get(FIELD_DAY).toString());
					db.dateParts(year, month, day);
				} else {
					db.dateParts(year, month);
				}
			} else {
				db.dateParts(year);
			}
			CSLDate d = db.build();
			builder.issued(d);
			builder.eventDate(d);
		}
		
		//convert number
		if (document.containsKey(FIELD_REVISION)) {
			builder.number(strOrNull(document.get(FIELD_REVISION)));
		} else {
			builder.number(strOrNull(document.get(FIELD_SERIES_NUMBER)));
		}
		
		//convert container title
		String containerTitle;
		if (document.containsKey(FIELD_SERIES)) {
			containerTitle = strOrNull(document.get(FIELD_SERIES));
		} else {
			containerTitle = strOrNull(document.get(FIELD_SOURCE));
		}
		builder.containerTitle(containerTitle);
		builder.collectionTitle(containerTitle);
		
		//convert publisher
		if (mtype.equalsIgnoreCase(TYPE_PATENT) && document.containsKey(FIELD_SOURCE)) {
			builder.publisher(strOrNull(document.get(FIELD_SOURCE)));
		} else {
			builder.publisher(strOrNull(document.get(FIELD_PUBLISHER)));
		}
		
		//convert access date
		if (document.containsKey(FIELD_ACCESSED)) {
			builder.accessed(new CSLDateBuilder().raw(
					strOrNull(document.get(FIELD_ACCESSED))).build());
		}
		
		//convert identifiers
		if (document.containsKey(FIELD_IDENTIFIERS)) {
			@SuppressWarnings("unchecked")
			Map<String, String> identifiers = (Map<String, String>)document.get(FIELD_IDENTIFIERS);
			builder.DOI(identifiers.get(IDENTIFIER_DOI));
			builder.ISBN(identifiers.get(IDENTIFIER_ISBN));
			builder.ISSN(identifiers.get(IDENTIFIER_ISSN));
			builder.PMID(identifiers.get(IDENTIFIER_PMID));
		}
		
		//convert keywords
		if (document.containsKey(FIELD_KEYWORDS)) {
			@SuppressWarnings("unchecked")
			List<String> keywords = (List<String>)document.get(FIELD_KEYWORDS);
			builder.keyword(StringUtils.join(keywords, ','));
		}
		
		//convert URL
		if (document.containsKey(FIELD_WEBSITES)) {
			@SuppressWarnings("unchecked")
			List<String> websites = (List<String>)document.get(FIELD_WEBSITES);
			if (websites.size() > 0) {
				//use the first website only
				builder.URL(websites.get(0));
			}
		}
		
		//convert other fields
		builder.abstrct(strOrNull(document.get(FIELD_ABSTRACT)));
		builder.chapterNumber(strOrNull(document.get(FIELD_CHAPTER)));
		builder.eventPlace(strOrNull(document.get(FIELD_CITY)));
		builder.publisherPlace(strOrNull(document.get(FIELD_CITY)));
		builder.edition(strOrNull(document.get(FIELD_EDITION)));
		builder.genre(strOrNull(document.get(FIELD_GENRE)));
		builder.issue(strOrNull(document.get(FIELD_ISSUE)));
		builder.language(strOrNull(document.get(FIELD_LANGUAGE)));
		builder.medium(strOrNull(document.get(FIELD_MEDIUM)));
		builder.page(strOrNull(document.get(FIELD_PAGES)));
		builder.shortTitle(strOrNull(document.get(FIELD_SHORT_TITLE)));
		builder.title(strOrNull(document.get(FIELD_TITLE)));
		builder.volume(strOrNull(document.get(FIELD_VOLUME)));
		
		return builder.build();
	}
785516
public CompactChangeEvent<DocumentT> withoutUncommittedWrites() {
    return new CompactChangeEvent<>(
        this.getOperationType(),
        this.getFullDocument(),
        this.getDocumentKey(),
        this.getUpdateDescription(),
        this.getStitchDocumentVersion(),
        this.getStitchDocumentHash(),
        false);
  }
1352159
public Document<K> addDocument(K id, String document)
    {
        return addDocument(id, preprocess(document));
    }
436801
public static Document toDocument(InputStream is) throws MarshalException {
		try {
			return newDocumentBuilder().parse(is);
		} catch (SAXException e) {
			IfmapJLog.error(e.getMessage());
			throw new MarshalException(e.getMessage());
		} catch (IOException e) {
			IfmapJLog.error(e.getMessage());
			throw new MarshalException(e.getMessage());
		}
	}
668316
public Organization parseDocument(Document doc) throws IOException, ParseException {
        Organization organization = new Organization();
        organization.setSherdogUrl(ParserUtils.getSherdogPageUrl(doc));

        String url= organization.getSherdogUrl();
        url += "/recent-events/%d";
        int page = 1;


        doc = ParserUtils.parseDocument(String.format(url, page));

        logger.info("Getting name");
        Elements name = doc.select(".bio_organization .module_header h2[itemprop=\"name\"]");
        organization.setName(name.html());


        logger.info("Getting upcoming event");
        Elements upcomingEventsElement = doc.select("#upcoming_tab .event tr");
        organization.getEvents().addAll(parseEvent(upcomingEventsElement, organization));

        logger.info("Getting past events");
        List<Event> toAdd;
        do {
            logger.info("Parsing page [{}]", page);

            doc = ParserUtils.parseDocument(String.format(url, page));
            Elements events = doc.select("#recent_tab .event tr");

            toAdd = parseEvent(events, organization);

            organization.getEvents().addAll(toAdd);
            page++;


        } while (toAdd.size() > 0);


        organization.getEvents().sort((o1, o2) -> o1.getDate().compareTo(o2.getDate()));
        return organization;
    }
1017055
public static EditableDocument newDocument( Document original ) {
        BasicDocument newDoc = new BasicDocument();
        newDoc.putAll(original);
        return new DocumentEditor(newDoc, DEFAULT_FACTORY);
    }
620463
public final BELScriptWalker.set_document_return set_document() throws RecognitionException {
        BELScriptWalker.set_document_return retval = new BELScriptWalker.set_document_return();
        retval.start = input.LT(1);

        CommonTree root_0 = null;

        CommonTree _first_0 = null;
        CommonTree _last = null;

        CommonTree dkt=null;
        CommonTree qv=null;
        CommonTree oi=null;
        CommonTree string_literal13=null;
        CommonTree char_literal14=null;
        BELScriptWalker.document_property_return prop = null;


        CommonTree dkt_tree=null;
        CommonTree qv_tree=null;
        CommonTree oi_tree=null;
        CommonTree string_literal13_tree=null;
        CommonTree char_literal14_tree=null;

        try {
            // BELScriptWalker.g:121:13: ( ( 'SET' dkt= DOCUMENT_KEYWORD ) prop= document_property '=' (qv= QUOTED_VALUE | oi= OBJECT_IDENT ) )
            // BELScriptWalker.g:122:5: ( 'SET' dkt= DOCUMENT_KEYWORD ) prop= document_property '=' (qv= QUOTED_VALUE | oi= OBJECT_IDENT )
            {
            root_0 = (CommonTree)adaptor.nil();

            // BELScriptWalker.g:122:5: ( 'SET' dkt= DOCUMENT_KEYWORD )
            // BELScriptWalker.g:122:6: 'SET' dkt= DOCUMENT_KEYWORD
            {
            _last = (CommonTree)input.LT(1);
            string_literal13=(CommonTree)match(input,24,FOLLOW_24_in_set_document144); 
            string_literal13_tree = (CommonTree)adaptor.dupNode(string_literal13);

            adaptor.addChild(root_0, string_literal13_tree);

            _last = (CommonTree)input.LT(1);
            dkt=(CommonTree)match(input,DOCUMENT_KEYWORD,FOLLOW_DOCUMENT_KEYWORD_in_set_document148); 
            dkt_tree = (CommonTree)adaptor.dupNode(dkt);

            adaptor.addChild(root_0, dkt_tree);


            }

            _last = (CommonTree)input.LT(1);
            pushFollow(FOLLOW_document_property_in_set_document153);
            prop=document_property();

            state._fsp--;

            adaptor.addChild(root_0, prop.getTree());
            _last = (CommonTree)input.LT(1);
            char_literal14=(CommonTree)match(input,25,FOLLOW_25_in_set_document155); 
            char_literal14_tree = (CommonTree)adaptor.dupNode(char_literal14);

            adaptor.addChild(root_0, char_literal14_tree);

            // BELScriptWalker.g:122:61: (qv= QUOTED_VALUE | oi= OBJECT_IDENT )
            int alt3=2;
            int LA3_0 = input.LA(1);

            if ( (LA3_0==QUOTED_VALUE) ) {
                alt3=1;
            }
            else if ( (LA3_0==OBJECT_IDENT) ) {
                alt3=2;
            }
            else {
                NoViableAltException nvae =
                    new NoViableAltException("", 3, 0, input);

                throw nvae;
            }
            switch (alt3) {
                case 1 :
                    // BELScriptWalker.g:122:62: qv= QUOTED_VALUE
                    {
                    _last = (CommonTree)input.LT(1);
                    qv=(CommonTree)match(input,QUOTED_VALUE,FOLLOW_QUOTED_VALUE_in_set_document160); 
                    qv_tree = (CommonTree)adaptor.dupNode(qv);

                    adaptor.addChild(root_0, qv_tree);


                    }
                    break;
                case 2 :
                    // BELScriptWalker.g:122:80: oi= OBJECT_IDENT
                    {
                    _last = (CommonTree)input.LT(1);
                    oi=(CommonTree)match(input,OBJECT_IDENT,FOLLOW_OBJECT_IDENT_in_set_document166); 
                    oi_tree = (CommonTree)adaptor.dupNode(oi);

                    adaptor.addChild(root_0, oi_tree);


                    }
                    break;

            }


                    if (!annotationContext.isEmpty() || !stmtlist.isEmpty()) {
                        addError(new SetDocumentPropertiesFirstException(dkt.getLine(), dkt.getCharPositionInLine()));
                    }

                    final String keywordValue;
                    if (qv != null) {
                        keywordValue = qv.toString();
                    } else if (oi != null) {
                        keywordValue = oi.toString();
                    } else {
                        throw new IllegalStateException("Did not understand document keyword value, expecting quoted value or object identifier.");
                    }

                    docprop.put(prop.r, keywordValue);
                    lastDocumentPropertyLocation = dkt.getLine();
                

            }

            retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);

        }
        catch (RecognitionException re) {
            reportError(re);
            recover(input,re);
        }
        finally {
        }
        return retval;
    }
1269460
public SimpleOrderedMap<Object> create(ComponentDocument document,
      Boolean encode) throws IOException {
    SimpleOrderedMap<Object> mtasDocumentResponse = new SimpleOrderedMap<>();
    mtasDocumentResponse.add("key", document.key);
    ArrayList<NamedList<Object>> mtasDocumentItemResponses = new ArrayList<>();
    for (int docId : document.statsData.keySet()) {
      NamedList<Object> mtasDocumentItemResponse = new SimpleOrderedMap<>();
      MtasDataCollector<?, ?> stats = document.statsData.get(docId);
      MtasDataCollector<?, ?> list = null;
      if (document.statsList != null) {
        list = document.statsList.get(docId);
      }
      mtasDocumentItemResponse.add("stats",
          new MtasSolrMtasResult(stats, stats.getDataType(),
              stats.getStatsType(), stats.getStatsItems(), null, null));
      mtasDocumentItemResponse.add("documentKey",
          document.uniqueKey.get(docId));
      if (list != null) {
        if (document.listExpand) {
          mtasDocumentItemResponse.add("list",
              new MtasSolrMtasResult(list,
                  new String[] { list.getDataType(), list.getDataType() },
                  new String[] { list.getStatsType(), list.getStatsType() },
                  new SortedSet[] { list.getStatsItems(),
                      list.getStatsItems() },
                  new List[] { null, null }, new String[] { null, null },
                  new String[] { null, null }, new Integer[] { 0, 0 },
                  new Integer[] { 1, 1 }, null));
        } else {
          mtasDocumentItemResponse.add("list",
              new MtasSolrMtasResult(list, list.getDataType(),
                  list.getStatsType(), list.getStatsItems(), null, null));
        }

      }
      // add
      mtasDocumentItemResponses.add(mtasDocumentItemResponse);
    }
    mtasDocumentResponse.add("list", mtasDocumentItemResponses);
    MtasSolrResultUtil.rewrite(mtasDocumentResponse, searchComponent);
    return mtasDocumentResponse;
  }
250318
private ChangeEvent<BsonDocument> getSynthesizedRemoteChangeEventForDocument(
      final MongoNamespace ns,
      final BsonValue documentId,
      final BsonDocument document
  ) {
    // a. When the document is looked up, if it cannot be found the synthesized change event is a
    // DELETE, otherwise it's a REPLACE.
    if (document == null) {
      return ChangeEvents.changeEventForLocalDelete(ns, documentId, false);
    }
    return ChangeEvents.changeEventForLocalReplace(ns, documentId, document, false);
  }
593877
@Override
    public <A> A fromXML(Document document, Class<A> clazz) {
        return fromXML(stringify(document), clazz);
    }
1027969
private DocumentChange addDoc(QueryDocumentSnapshot newDocument) {
    ResourcePath resourcePath = newDocument.getReference().getResourcePath();
    documentSet = documentSet.add(newDocument);
    int newIndex = documentSet.indexOf(resourcePath);
    return new DocumentChange(newDocument, Type.ADDED, -1, newIndex);
  }
278708
public static InputStream documentToPrettyInputStream(Node document) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        Source xmlSource = new DOMSource(document);
        Result outputTarget = new StreamResult(outputStream);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.transform(xmlSource, outputTarget);

        InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
        return is;
    }
451208
static BsonDocument getFreshVersionDocument() {
    final BsonDocument versionDoc = new BsonDocument();

    versionDoc.append(Fields.SYNC_PROTOCOL_VERSION_FIELD, new BsonInt32(1));
    versionDoc.append(Fields.INSTANCE_ID_FIELD, new BsonString(UUID.randomUUID().toString()));
    versionDoc.append(Fields.VERSION_COUNTER_FIELD, new BsonInt64(0L));

    return versionDoc;
  }
767644
@Override
    public Document createDocument(Document parentDocument) {
        Ruby runtime = JRubyRuntimeContext.get(parentDocument);
        RubyHash options = RubyHash.newHash(runtime);
        options.put(
                runtime.newSymbol("parent"),
                ((DocumentImpl) parentDocument).getRubyObject());

        return (Document) NodeConverter.createASTNode(runtime, NodeConverter.NodeType.DOCUMENT_CLASS, runtime.getNil(), options);
    }