private RequestOptions getRequestOptions(String key) { RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(key)); return requestOptions; }
@Override public Status update(String table, String key, Map<String, ByteIterator> values) { String documentLink = getDocumentLink(this.databaseName, table, key); Document document = getDocumentDefinition(key, values); RequestOptions reqOptions = getRequestOptions(key); if (reqOptions == null) { reqOptions = new RequestOptions(); } AccessCondition accessCondition = new AccessCondition(); accessCondition.setCondition(document.getETag()); accessCondition.setType(AccessConditionType.IfMatch); reqOptions.setAccessCondition(accessCondition); ResourceResponse<Document> updatedResource = null; long startTime = System.nanoTime(); try { updatedResource = AzureCosmosClient.client.replaceDocument(documentLink, document, reqOptions); } catch (DocumentClientException e) { if (!this.includeExceptionStackInLog) { e = null; } LOGGER.error("Failed to update key {}", key, e); return Status.ERROR; } finally { long elapsed = (System.nanoTime() - startTime) / NS_IN_US; LOGGER.debug("Updated key {} in {}us - ActivityID: {}", key, elapsed, updatedResource != null ? updatedResource.getActivityId() : NA_STRING); } return Status.OK; }
Map<String, String> customOptions = options.getCustomRequestOptions(); if (customOptions != null) { headers.putAll(customOptions); if (options.getAccessCondition() != null) { if (options.getAccessCondition().getType() == AccessConditionType.IfMatch) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getAccessCondition().getCondition()); } else { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getAccessCondition().getCondition()); if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().name()); if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().name()); if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); if (options.getSessionToken() != null && !options.getSessionToken().isEmpty()) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
private RequestOptions getRequestOptions(PartitionKey key, Integer requestUnit) { if (key == null && requestUnit == null) { return null; } final RequestOptions requestOptions = new RequestOptions(); if (key != null) { requestOptions.setPartitionKey(key); } if (requestUnit != null) { requestOptions.setOfferThroughput(requestUnit); } return requestOptions; }
private DocumentCollection createCollectionIfNotExists(String dbName, String collectionName) { if (this.databaseCache == null) { this.databaseCache = createDatabaseIfNotExists(dbName); } final List<DocumentCollection> collectionList = documentDbFactory.getDocumentClient() .queryCollections(getDatabaseLink(dbName), new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", collectionName))), null) .getQueryIterable().toList(); if (!collectionList.isEmpty()) { return collectionList.get(0); } else { final RequestOptions requestOptions = new RequestOptions(); requestOptions.setOfferThroughput(1000); return createCollection(dbName, collectionName, requestOptions); } }
AzureCosmosClient.client.readDatabase(getDatabaseLink(this.databaseName), new RequestOptions()); } catch (DocumentClientException e) { throw new DBException("Invalid database name (" + this.databaseName + ") or failed to read database.", e);
final RequestOptions optionsLocal = options; final boolean disableAutomaticIdGenerationLocal = disableAutomaticIdGeneration; final boolean shouldRetry = options == null || options.getPartitionKey() == null;
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); if (options != null) { if (options.getPartitionKey() != null) { requestHeaders.put(HttpConstants.HttpHeaders.PARTITION_KEY, options.getPartitionKey().toString()); if (options.getPartitionKeyRangeId() != null) { requestHeaders.put(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID, options.getPartitionKeyRangeId()); if (options.isScriptLoggingEnabled()) { requestHeaders.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); procedureParams != null ? DocumentClient.serializeProcedureParams(procedureParams, objectMapper) : "", requestHeaders); if (options != null && options.getPartitionKeyRangeId() != null) { PartitionKeyRangeIdentity partitionKeyRangeId = new PartitionKeyRangeIdentity(options.getPartitionKeyRangeId()); request.setPartitionKeyRangeIdentity(partitionKeyRangeId); } else {
private RequestOptions getRequestOptions(PartitionKey key, Integer requestUnit) { if (key == null && requestUnit == null) { return null; } final RequestOptions requestOptions = new RequestOptions(); if (key != null) { requestOptions.setPartitionKey(key); } if (requestUnit != null) { requestOptions.setOfferThroughput(requestUnit); } return requestOptions; }
public <T> T findById(String collectionName, Object id, Class<T> entityClass) { try { final Resource resource = documentDbFactory.getDocumentClient() .readDocument(getDocumentLink(this.databaseName, collectionName, id), new RequestOptions()).getResource(); if (resource instanceof Document) { final Document document = (Document) resource; return mappingDocumentDbConverter.read(entityClass, document); } else { return null; } } catch (DocumentClientException e) { if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return null; } throw new DocumentDBAccessException("findById exception", e); } }
void addPartitionKeyInformation(AbstractDocumentServiceRequest request, Document document, RequestOptions options) { PartitionKeyInternal partitionKeyInternal; if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = options.getPartitionKey().getInternalPartitionKey(); } else { // Resolve collection only when it's needed DocumentCollection collection = this.collectionCache.resolveCollection(request); PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { // For backward compatibility, if collection doesn't have partition key defined, we assume all documents // have empty value for it and user doesn't need to specify it explicitly. partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (document != null) { partitionKeyInternal = extractPartitionKeyValueFromDocument(document, partitionKeyDefinition); } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } } request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, escapeNonAscii(partitionKeyInternal.toJson())); }
private void deleteDocument(@NonNull Document document, @NonNull List<String> partitionKeyNames) { try { final RequestOptions options = new RequestOptions(); Assert.isTrue(partitionKeyNames.size() <= 1, "Only one Partition is supported."); if (!partitionKeyNames.isEmpty() && StringUtils.hasText(partitionKeyNames.get(0))) { options.setPartitionKey(new PartitionKey(document.get(partitionKeyNames.get(0)))); } getDocumentClient().deleteDocument(document.getSelfLink(), options); } catch (DocumentClientException e) { throw new DocumentDBAccessException("Failed to delete document: " + document.getSelfLink(), e); } }
final RequestOptions optionsLocal = options; final boolean disableAutomaticIdGenerationLocal = disableAutomaticIdGeneration; final boolean shouldRetry = options == null || options.getPartitionKey() == null;
public <T> T findById(String collectionName, Object id, Class<T> domainClass) { Assert.hasText(collectionName, "collectionName should not be null, empty or only whitespaces"); Assert.notNull(domainClass, "entityClass should not be null"); assertValidId(id); try { final RequestOptions options = new RequestOptions(); if (isIdFieldAsPartitionKey(domainClass)) { options.setPartitionKey(new PartitionKey(id)); } final String documentLink = getDocumentLink(this.databaseName, collectionName, id); final Resource document = getDocumentClient().readDocument(documentLink, options).getResource(); if (document instanceof Document) { return mappingDocumentDbConverter.read(domainClass, (Document) document); } else { return null; } } catch (DocumentClientException e) { if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return null; } throw new DocumentDBAccessException("findById exception", e); } }
final RequestOptions optionsLocal = options; final boolean disableAutomaticIdGenerationLocal = disableAutomaticIdGeneration; final boolean shouldRetry = options == null || options.getPartitionKey() == null;
@Override public <T> List<T> delete(Query query, Class<T> entityClass, String collectionName) { final SqlQuerySpec sqlQuerySpec = createSqlQuerySpec(query, entityClass); final Optional<Object> partitionKeyValue = getPartitionKeyValue(query, entityClass); final DocumentCollection collection = getDocCollection(collectionName); final FeedOptions feedOptions = new FeedOptions(); if (!partitionKeyValue.isPresent()) { feedOptions.setEnableCrossPartitionQuery(true); } final List<Document> results = documentDbFactory.getDocumentClient() .queryDocuments(collection.getSelfLink(), sqlQuerySpec, feedOptions).getQueryIterable().toList(); final RequestOptions options = new RequestOptions(); if (partitionKeyValue.isPresent()) { options.setPartitionKey(new PartitionKey(partitionKeyValue.get())); } final List<T> deletedResult = new ArrayList<>(); for (final Document document : results) { try { documentDbFactory.getDocumentClient().deleteDocument((document).getSelfLink(), options); deletedResult.add(getConverter().read(entityClass, document)); } catch (DocumentClientException e) { throw new DocumentDBAccessException( String.format("Failed to delete document [%s]", (document).getSelfLink()), e); } } return deletedResult; }
final RequestOptions optionsLocal = options; final boolean disableAutomaticIdGenerationLocal = disableAutomaticIdGeneration; final boolean shouldRetry = options == null || options.getPartitionKey() == null; Observable<ResourceResponse<Document>> createObservable = Observable.defer(() -> {
private ResourceResponse<Document> replaceDocumentInternal(String documentLink, Document document, RequestOptions options) throws DocumentClientException { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String documentCollectionName = Utils.getCollectionName(documentLink); final String documentCollectionLink = this.getTargetDocumentCollectionLink(documentCollectionName, document); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options); final DocumentServiceRequest request = DocumentServiceRequest.create(OperationType.Replace, ResourceType.Document, path, document, requestHeaders); this.addPartitionKeyInformation(request, document, options); final boolean shouldRetry = options == null || options.getPartitionKey() == null; DocumentClient.validateResource(document); RetryCreateDocumentDelegate replaceDelegate = new RetryCreateDocumentDelegate() { @Override public ResourceResponse<Document> apply() throws DocumentClientException { return new ResourceResponse<Document>(doReplace(request), Document.class); } }; return shouldRetry ? RetryUtility.executeCreateDocument(replaceDelegate, this.collectionCache, documentCollectionLink) : replaceDelegate.apply(); }
private Observable<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options) throws DocumentClientException { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String documentCollectionName = Utils.getCollectionName(documentLink); final String documentCollectionLink = this.getTargetDocumentCollectionLink(documentCollectionName, document); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.Document, path, document, requestHeaders); final boolean shouldRetry = options == null || options.getPartitionKey() == null; // NOTE: if the collection is not cached this will block till collection // is retrieved DocumentCollection collection = this.collectionCache.resolveCollection(request); this.addPartitionKeyInformation(request, document, options, collection); validateResource(document); Observable<ResourceResponse<Document>> resourceResponseObs = this.doReplace(request) .map(resp -> toResourceResponse(resp, Document.class)); if (shouldRetry) { CreateDocumentRetryHandler createDocumentRetryHandler = new CreateDocumentRetryHandler(null, documentCollectionLink); return resourceResponseObs.retryWhen(RetryFunctionFactory.from(createDocumentRetryHandler)); } else { return resourceResponseObs; } }