/*
TransientDocuments
506780
public function uploadTransientDocument(MultipartStream $multipartStream, array $headers = [])
    {
        $request = $this->provider->getAuthenticatedRequest(
            'POST',
            "$this->baseUri/$this->version/transientDocuments",
            $this->accessToken, [
                'headers' => $headers,
                'body' => $multipartStream
            ]
        );

        $res = $this->provider->getResponse($request);

        return $this->parseResponse($res);
    }
643650
public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
			OutputStream entityStream) throws IOException, WebApplicationException {
		SerializeFilter filter = null;

        if(pretty) {
			if (fastJsonConfig.serializerFeatures == null)
				fastJsonConfig.serializerFeatures = new  SerializerFeature[]{SerializerFeature.PrettyFormat};
            else {
                List<SerializerFeature> serializerFeatures = Arrays.asList(fastJsonConfig.serializerFeatures);
                serializerFeatures.add(SerializerFeature.PrettyFormat);
                fastJsonConfig.serializerFeatures = serializerFeatures.toArray(new SerializerFeature[]{});
            }
		}

		if (fastJsonConfig.serializeFilters != null)
			filter = fastJsonConfig.serializeFilters.get(type);
		String jsonStr = toJSONString(t, filter, fastJsonConfig.serializerFeatures);
		if (jsonStr != null)
			entityStream.write(jsonStr.getBytes());
	}
232148
public void writeCollection(BioCCollection collection)
      throws XMLStreamException {
    if (hasWritten) {
      throw new IllegalStateException(
          "writeCollection can only be invoked once.");
    }
    hasWritten = true;

    writer.writeStartDocument(
        collection.getEncoding(),
        collection.getVersion(),
        collection.isStandalone())
        .writeBeginCollectionInfo(collection);

    for (BioCDocument doc : collection.getDocuments()) {
      writer.write(doc);
    }

    // end collection
    writer.writeEndCollection()
        .writeEndDocument();
  }
501808
function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
  var metaDocId = '_local/doc_' + docId;
  var defaultMetaDoc = {_id: metaDocId, keys: []};
  var docData = docIdsToChangesAndEmits[docId];
  var indexableKeysToKeyValues = docData.indexableKeysToKeyValues;
  var changes = docData.changes;

  function getMetaDoc() {
    if (isGenOne(changes)) {
      // generation 1, so we can safely assume initial state
      // for performance reasons (avoids unnecessary GETs)
      return Promise.resolve(defaultMetaDoc);
    }
    return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc));
  }

  function getKeyValueDocs(metaDoc) {
    if (!metaDoc.keys.length) {
      // no keys, no need for a lookup
      return Promise.resolve({rows: []});
    }
    return view.db.allDocs({
      keys: metaDoc.keys,
      include_docs: true
    });
  }

  function processKvDocs(metaDoc, kvDocsRes) {
    var kvDocs = [];
    var oldKeysMap = {};

    for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {
      var row = kvDocsRes.rows[i];
      var doc = row.doc;
      if (!doc) { // deleted
        continue;
      }
      kvDocs.push(doc);
      oldKeysMap[doc._id] = true;
      doc._deleted = !indexableKeysToKeyValues[doc._id];
      if (!doc._deleted) {
        var keyValue = indexableKeysToKeyValues[doc._id];
        if ('value' in keyValue) {
          doc.value = keyValue.value;
        }
      }
    }

    var newKeys = Object.keys(indexableKeysToKeyValues);
    newKeys.forEach(function (key) {
      if (!oldKeysMap[key]) {
        // new doc
        var kvDoc = {
          _id: key
        };
        var keyValue = indexableKeysToKeyValues[key];
        if ('value' in keyValue) {
          kvDoc.value = keyValue.value;
        }
        kvDocs.push(kvDoc);
      }
    });
    metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));
    kvDocs.push(metaDoc);

    return kvDocs;
  }

  return getMetaDoc().then(function (metaDoc) {
    return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {
      return processKvDocs(metaDoc, kvDocsRes);
    });
  });
}
631207
@Nullable
  private DocumentChange modifyDoc(QueryDocumentSnapshot newDocument) {
    ResourcePath resourcePath = newDocument.getReference().getResourcePath();
    DocumentSnapshot oldDocument = documentSet.getDocument(resourcePath);

    if (!oldDocument.getUpdateTime().equals(newDocument.getUpdateTime())) {
      int oldIndex = documentSet.indexOf(resourcePath);
      documentSet = documentSet.remove(resourcePath);
      documentSet = documentSet.add(newDocument);
      int newIndex = documentSet.indexOf(resourcePath);
      return new DocumentChange(newDocument, Type.MODIFIED, oldIndex, newIndex);
    }
    return null;
  }
655894
function whenDocumentReady(callback, doc) {
  if (!isDocumentReady(doc)) {
    var checkReady = function() {
      if (doc.readyState === 'complete' ||
          doc.readyState === requiredReadyState) {
        doc.removeEventListener(READY_EVENT, checkReady);
        whenDocumentReady(callback, doc);
      }
    };
    doc.addEventListener(READY_EVENT, checkReady);
  } else if (callback) {
    callback();
  }
}
1291946
function getDocument(element, callback) {
                        //Opera 12 seem to call the object.onload before the actual document has been created.
                        //So if it is not present, poll it with an timeout until it is present.
                        //TODO: Could maybe be handled better with object.onreadystatechange or similar.
                        if(!element.contentDocument) {
                            setTimeout(function checkForObjectDocument() {
                                getDocument(element, callback);
                            }, 100);

                            return;
                        }

                        callback(element.contentDocument);
                    }
27186
public void doSendDocument(Peer peer, String fileName, String mimeType, int fileSize,
                               FastThumb fastThumb, String descriptor) {
        long rid = RandomUtils.nextRid();
        long date = createPendingDate();
        long sortDate = date + 365 * 24 * 60 * 60 * 1000L;
        DocumentContent documentContent = DocumentContent.createLocal(fileName, fileSize,
                descriptor, mimeType, fastThumb);

        Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, documentContent);
        context().getMessagesModule().getRouter().onOutgoingMessage(peer, message);

        pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, documentContent));
        savePending();

        performUploadFile(rid, descriptor, fileName);
    }
3058
private void forEachFieldDo(FieldCallBack fieldCallBack) {
		Class<?> clazz = this.getClass();
		
		while (true) {
			
			Field[] fields = clazz.getDeclaredFields();
			try {
				for (Field field : fields) {
					// FIXME: test skipped cases
					// skip Logger object
					if (field.getType() == Logger.class)
						continue;
					// skip fields annotated with @Transient
					if (field.getAnnotation(Transient.class) != null)
						continue;
					// skip serialVersionUID
					if ("serialVersionUID".equals(field.getName()))
						continue;
					field.setAccessible(true);
					fieldCallBack.doForField(field);
				} 
			} catch (IllegalArgumentException e) {
				throw new RuntimeException(e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
			
			if (clazz.getName().equals(DataObject.class.getName()))
				break;
			
			clazz = clazz.getSuperclass();
		}
	}
573642
void addDocuments(final Document[] docs) throws IOException
   {
      final IndexWriter writer = getIndexWriter();

      IOException ioExc = null;
      try
      {
         for (Document doc : docs)
         {
            try
            {
               writer.addDocument(doc);
            }
            catch (Throwable e) //NOSONAR
            {
               if (ioExc == null)
               {
                  if (e instanceof IOException)
                  {
                     ioExc = (IOException)e;
                  }
                  else
                  {
                     ioExc = Util.createIOException(e);
                  }
               }

               log.warn("Exception while inverting document", e);
            }
         }
      }
      finally
      {
         invalidateSharedReader();
      }

      if (ioExc != null)
      {
         throw ioExc;
      }
   }
1297965
@Override
  public int nextDoc() throws IOException {
    docId = NO_MORE_DOCS;
    currentStartPosition = NO_MORE_POSITIONS;
    currentEndPosition = NO_MORE_POSITIONS;
    return docId;
  }
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);
  }
978416
public void startDocument() throws SAXException
  {

    int doc = addNode(DTM.DOCUMENT_NODE,
                      DTM.DOCUMENT_NODE,
                      DTM.NULL, DTM.NULL, 0, true);

    m_parents.push(doc);
    m_previous = DTM.NULL;

    m_contextIndexes.push(m_prefixMappings.size());  // for the next element.
  }
869593
@Nullable
  private XTextDocument getCurrentDocument(XComponentContext xContext) {
    try {
      XComponent curComp = OfficeTools.getCurrentComponent(xContext);
      if (curComp == null) {
        return null;
      }
      else return UnoRuntime.queryInterface(XTextDocument.class, curComp);
    } catch (Throwable t) {
      MessageHandler.printException(t);     // all Exceptions thrown by UnoRuntime.queryInterface are caught
      return null;           // Return null as method failed
    }
  }
1254129
synchronized int removeAllDocuments(String uuid) throws IOException
   {
      synchronized (updateMonitor)
      {
         //updateInProgress = true;
         indexUpdateMonitor.setUpdateInProgress(true, false);
      }
      int num;
      try
      {
         Term idTerm = new Term(FieldNames.UUID, uuid.toString());
         executeAndLog(new Start(Action.INTERNAL_TRANSACTION));
         num = volatileIndex.removeDocument(idTerm);
         if (num > 0)
         {
            redoLog.append(new DeleteNode(getTransactionId(), uuid));
         }
         for (int i = 0; i < indexes.size(); i++)
         {
            PersistentIndex index = indexes.get(i);
            // only remove documents from registered indexes
            if (indexNames.contains(index.getName()))
            {
               int removed = index.removeDocument(idTerm);
               if (removed > 0)
               {
                  redoLog.append(new DeleteNode(getTransactionId(), uuid));
               }
               num += removed;
            }
         }
         executeAndLog(new Commit(getTransactionId()));
      }
      finally
      {
         synchronized (updateMonitor)
         {
            //updateInProgress = false;
            indexUpdateMonitor.setUpdateInProgress(false, false);
            updateMonitor.notifyAll();
            releaseMultiReader();
         }
      }
      return num;
   }
216007
function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
  var seqDocId = '_local/lastSeq';
  return view.db.get(seqDocId)
  .catch(defaultsTo({_id: seqDocId, seq: 0}))
  .then(function (lastSeqDoc) {
    var docIds = Object.keys(docIdsToChangesAndEmits);
    return Promise.all(docIds.map(function (docId) {
      return getDocsToPersist(docId, view, docIdsToChangesAndEmits);
    })).then(function (listOfDocsToPersist) {
      var docsToPersist = flatten(listOfDocsToPersist);
      lastSeqDoc.seq = seq;
      docsToPersist.push(lastSeqDoc);
      // write all docs in a single operation, update the seq once
      return view.db.bulkDocs({docs : docsToPersist});
    });
  });
}
69443
private Document readDocument(byte[] xhtmlData) throws ParserConfigurationException, SAXException, IOException {

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docbuilder = docBuilderFactory.newDocumentBuilder();
        // use special entity resolver so we don't fetch the DTDs from w3.org, which would be slow
        docbuilder.setEntityResolver(m_entityResolver);
        Document doc = docbuilder.parse(new ByteArrayInputStream(xhtmlData));
        return doc;
    }