@Override public Status delete(String table, String key) { Document record = getDocumentById(table, key); try { // Delete the document by self link. documentClient.deleteDocument(record.getSelfLink(), null); } catch (DocumentClientException e) { e.printStackTrace(); return Status.ERROR; } return Status.OK; }
private Observable<Long> handleRetryAttemptInternal(DocumentClientException e, int attemptNumber) throws DocumentClientException { RetryPolicy retryPolicy = null; if (e.getStatusCode() == HttpConstants.StatusCodes.BADREQUEST && e.getSubStatusCode() != null && e.getSubStatusCode() == HttpConstants.SubStatusCodes.PARTITION_KEY_MISMATCH) { // If HttpStatusCode is 404 (NotFound) and SubStatusCode is // 1001 (PartitionKeyMismatch), invoke the partition key mismatch retry policy retryPolicy = keyMismatchRetryPolicy; } if (retryPolicy == null || !retryPolicy.shouldRetry(e)) { LOGGER.trace("Execution encontured exception: {}, status code {} sub status code {}. Won't retry!", e.getMessage(), e.getStatusCode(), e.getSubStatusCode()); return Observable.error(e); } LOGGER.trace("Execution encontured exception: {}, status code {} sub status code {}. Will retry in {}ms", e.getMessage(), e.getStatusCode(), e.getSubStatusCode(), retryPolicy.getRetryAfterInMilliseconds()); long waitTime = retryPolicy.getRetryAfterInMilliseconds(); return Observable.just(waitTime); } }
public void deleteAll(String collectionName) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("execute deleteCollection in database {} collection {} with id {}", this.databaseName, collectionName); } try { documentDbFactory.getDocumentClient() .deleteCollection(getCollectionLink(this.databaseName, collectionName), null); if (this.collectionCache.contains(collectionName)) { this.collectionCache.remove(collectionName); } } catch (DocumentClientException ex) { if (ex.getStatusCode() == 404) { LOGGER.warn("deleteAll in database {} collection {} met NOTFOUND error {}", this.databaseName, collectionName, ex.getMessage()); } else { throw new RuntimeException("deleteAll exception", ex); } } }
private static Observable<Long> handleRetryAttempt(Throwable t, int attemptNumber, RxRetryHandler retryPolicy) { Throwable cause = extractDocumentClientCause(t, attemptNumber); if (LOGGER.isDebugEnabled()) { if (cause instanceof DocumentClientException) { DocumentClientException ex = (DocumentClientException) cause; LOGGER.debug("Handling Failure Attempt [{}], StatusCode [{}], SubStatusCode," + " Error: [{}] ", attemptNumber, ex.getStatusCode(), ex.getSubStatusCode(), ex.getError(), ex); } else { LOGGER.debug("Handling Failure Attempt [{}], req [{}]", attemptNumber, cause); } } try { return retryPolicy.handleRetryAttempt(cause, attemptNumber); } catch (Exception e) { return Observable.error(e); } } }
public <T> T findById(String collectionName, Object id, Class<T> entityClass) { try { final Resource resource = documentDbFactory.getDocumentClient() .readDocument( getDocumentLink(this.databaseName, collectionName, id.toString()), null) .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 RuntimeException("findById exception", e); } }
public DatabaseAccount getDatabaseAccountFromAnyEndpoint() { DatabaseAccount databaseAccount = null; try { databaseAccount = this.client.getDatabaseAccountFromEndpoint(this.defaultEndpoint); } catch (DocumentClientException e) { this.logger.warn("Failed to retrieve database account information. {}", e.toString()); } // The global endpoint was not working. Try other endpoints in the preferred read region list. Collection<String> preferredLocations = this.locationCache.getPreferredLocations(); if (databaseAccount == null && preferredLocations != null && preferredLocations.size() > 0) { for (String regionName : preferredLocations) { URI regionalUri = this.getRegionalEndpoint(regionName); if (regionalUri != null) { try { databaseAccount = this.client.getDatabaseAccountFromEndpoint(regionalUri); break; } catch (DocumentClientException e) { this.logger.warn("Failed to retrieve database account information. {}", e.toString()); } } } } return databaseAccount; }
private void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatus status, HttpResponseHeaders headers, InputStream inputStream) throws DocumentClientException { int statusCode = status.code(); if (statusCode >= HttpConstants.StatusCodes.MINIMUM_STATUSCODE_AS_ERROR_GATEWAY) { String body = null; if (inputStream != null) { try { body = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (ParseException | IOException e) { logger.error("Failed to get content from the http response", e); throw new IllegalStateException("Failed to get content from the http response", e); } finally { IOUtils.closeQuietly(inputStream); } } Map<String, String> responseHeaders = new HashMap<String, String>(); for (Entry<String, String> header : headers.entries()) { responseHeaders.put(header.getKey(), header.getValue()); } String statusCodeString = status.reasonPhrase() != null ? status.reasonPhrase().replace(" ", "") : ""; Error error = null; error = (body != null)? new Error(body): new Error(); error = new Error(statusCodeString, String.format("%s, StatusCode: %s", error.getMessage(), statusCodeString), error.getPartitionedQueryExecutionInfo()); throw new DocumentClientException(statusCode, error, responseHeaders); } }
if (e.getStatusCode() == HttpConstants.StatusCodes.FORBIDDEN && e.getSubStatusCode() != null && e.getSubStatusCode() == HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN) { } else if (e.getStatusCode() == HttpConstants.StatusCodes.TOO_MANY_REQUESTS) { } else if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND && e.getSubStatusCode() != null && e.getSubStatusCode() == HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE) { e.getMessage(), e.getStatusCode(), e.getSubStatusCode()); return Observable.error(e); e.getMessage(), e.getStatusCode(), e.getSubStatusCode(), retryPolicy.getRetryAfterInMilliseconds());
public void deleteAll(String collectionName) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("execute deleteCollection in database {} collection {}", this.databaseName, collectionName); } try { documentDbFactory.getDocumentClient() .deleteCollection(getCollectionLink(this.databaseName, collectionName), null); if (this.collectionCache.contains(collectionName)) { this.collectionCache.remove(collectionName); } } catch (DocumentClientException ex) { if (ex.getStatusCode() == 404) { LOGGER.warn("deleteAll in database {} collection {} met NOTFOUND error {}", this.databaseName, collectionName, ex.getMessage()); } else { throw new DocumentDBAccessException("deleteAll exception", ex); } } }
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); } }
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); } }
@Override public Status update(String table, String key, Map<String, ByteIterator> values) { Document record = getDocumentById(table, key); if (record == null) { return Status.ERROR; } // Update each field. for (Entry<String, ByteIterator> val : values.entrySet()) { record.set(val.getKey(), val.getValue().toString()); } // Replace the document. try { documentClient.replaceDocument(record, null); } catch (DocumentClientException e) { e.printStackTrace(System.err); return Status.ERROR; } return Status.OK; }
@Override public Status insert(String table, String key, Map<String, ByteIterator> values) { Document record = new Document(); record.set("id", key); for (Entry<String, ByteIterator> val : values.entrySet()) { record.set(val.getKey(), val.getValue().toString()); } try { documentClient.createDocument(collection.getSelfLink(), record, null, false); } catch (DocumentClientException e) { e.printStackTrace(System.err); return Status.ERROR; } return Status.OK; }
private Database getDatabase() { if (database == null) { // Get the database if it exists List<Database> databaseList = documentClient .queryDatabases( "SELECT * FROM root r WHERE r.id='" + databaseId + "'", null) .getQueryIterable() .toList(); if (databaseList.size() > 0) { // Cache the database object so we won't have to query for it // later to retrieve the selfLink. database = databaseList.get(0); } else { // Create the database if it doesn't exist. try { Database databaseDefinition = new Database(); databaseDefinition.setId(databaseId); database = documentClient.createDatabase(databaseDefinition, null) .getResource(); } catch (DocumentClientException e) { // TODO: Something has gone terribly wrong - the app wasn't // able to query or create the collection. // Verify your connection, endpoint, and key. e.printStackTrace(System.err); } } } return database; }
e.printStackTrace(System.err); throw e;