default Document getPatchedDocument(RetrieveLatestDao retrieveLatestDao, PatchRequest request, Optional<Long> optionalTimestamp ) throws OriginalNotFoundException, IOException { String guid = request.getGuid(); String sensorType = request.getSensorType(); String documentID = null; Long timestamp = optionalTimestamp.orElse(System.currentTimeMillis()); Map<String, Object> originalSource = request.getSource(); if (originalSource == null) { // no document source provided, lookup the latest Document toPatch = retrieveLatestDao.getLatest(guid, sensorType); if(toPatch != null && toPatch.getDocument() != null) { originalSource = toPatch.getDocument(); documentID = toPatch.getDocumentID().orElse(null); } else { String error = format("Document does not exist, but is required; guid=%s, sensorType=%s", guid, sensorType); throw new OriginalNotFoundException(error); } } Map<String, Object> patchedSource = JSONUtils.INSTANCE.applyPatch(request.getPatch(), originalSource); return new Document(patchedSource, guid, sensorType, timestamp, documentID); } }