private Document getDocumentById(String collectionId, String id) { if (collection == null) { return null; } // Retrieve the document using the DocumentClient. List<Document> documentList = documentClient .queryDocuments(collection.getSelfLink(), "SELECT * FROM root r WHERE r.id='" + id + "'", feedOptions) .getQueryIterable() .toList(); if (documentList.size() > 0) { return documentList.get(0); } return null; } }
new SqlParameter("@startkey", startkey))), getFeedOptions(startkey)); documents = feedResponse.getQueryIterable().toList(); } catch (Exception e) { if (!this.includeExceptionStackInLog) { LOGGER.debug("Queried {} records for key {} in {}us - ActivityID: {}", recordcount, startkey, elapsed, feedResponse != null ? feedResponse.getActivityId() : NA_STRING);
FeedResponse<T> feedResponse = impl.invoke(); final QueryIterable<T> qi = feedResponse.getQueryIterable(); Map<String, String> header = feedResponse.getResponseHeaders(); logger.trace("Page Header key/value map {}", header); int pageSize = getHeaderItemCount(header); if (pageResults.isEmpty() && (feedResponse.getResponseContinuation() == null || isChangeFeed)) { new FeedResponsePage<T>(pageResults, feedResponse.getResponseHeaders(), isChangeFeed); subscriber.onNext(frp); numberOfPages++; subscriber.onNext(new FeedResponsePage<>(new ArrayList<>(), feedResponse.getResponseHeaders(), isChangeFeed));
/** * Reads all databases. * * @param options the feed options. * @return the feed response with the read databases. */ public FeedResponse<Database> readDatabases(FeedOptions options) { logger.debug("Reading Databases."); return new FeedResponse<Database>(new QueryIterable<Database>(this, ResourceType.Database, Database.class, Paths.DATABASES_ROOT, options)); }
@Override public <T> Page<T> paginationQuery(DocumentQuery query, Class<T> domainClass, String collectionName) { Assert.isTrue(query.getPageable().getPageSize() > 0, "pageable should have page size larger than 0"); Assert.hasText(collectionName, "collection should not be null, empty or only whitespaces"); final Pageable pageable = query.getPageable(); final FeedOptions feedOptions = new FeedOptions(); if (pageable instanceof DocumentDbPageRequest) { feedOptions.setRequestContinuation(((DocumentDbPageRequest) pageable).getRequestContinuation()); } feedOptions.setPageSize(pageable.getPageSize()); feedOptions.setEnableCrossPartitionQuery(query.isCrossPartitionQuery(getPartitionKeyNames(domainClass))); final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generate(query); final FeedResponse<Document> response = executeQuery(sqlQuerySpec, feedOptions, collectionName); final Iterator<Document> it = response.getQueryIterator(); final List<T> result = new ArrayList<>(); for (int index = 0; it.hasNext() && index < pageable.getPageSize(); index++) { // Limit iterator as inner iterator will automatically fetch the next page final Document doc = it.next(); if (doc == null) { continue; } final T entity = mappingDocumentDbConverter.read(domainClass, doc); result.add(entity); } final DocumentDbPageRequest pageRequest = DocumentDbPageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), response.getResponseContinuation()); return new PageImpl<>(result, pageRequest, count(query, domainClass, collectionName)); }
/** * Gets the flag associated with the response from the Azure Cosmos DB * database service whether this feed request is served from Request * Units(RUs)/minute capacity or not. * * @return True if this request is served from RUs/minute capacity. * Otherwise, false. */ public boolean getRUPerMinuteUsed() { String value = this.getResponseHeaders().get(HttpConstants.HttpHeaders.IS_RU_PER_MINUTE_USED); if (StringUtils.isEmpty(value) || "0".equals(value) || "false".equals(value.toLowerCase())) { return false; } else { return true; } }
/** * Reads all users in a database. * * @param databaseLink the database link. * @param options the feed options. * @return the feed response with the read users. */ public FeedResponse<User> readUsers(String databaseLink, FeedOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading Users. databaseLink [{}]", databaseLink); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); return new FeedResponse<User>(new QueryIterable<User>(this, ResourceType.User, User.class, path, options)); }
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; }
/** * Query for databases. * * @param querySpec the SQL query specification. * @param options the feed options. * @return the feed response with the obtained databases. */ public FeedResponse<Database> queryDatabases(SqlQuerySpec querySpec, FeedOptions options) { if (querySpec == null) { throw new IllegalArgumentException("querySpec"); } logger.debug("Querying Databases. querySpec: [{}]", querySpec); return new FeedResponse<Database>(new QueryIterable<Database>(this, ResourceType.Database, Database.class, Paths.DATABASES_ROOT, querySpec, options)); }
collectionId + "'", null) .getQueryIterable() .toList();
/** * Reads all user defined functions in a document collection. * * @param collectionLink the collection link. * @param options the feed options. * @return the feed response with the read user defined functions. */ public FeedResponse<UserDefinedFunction> readUserDefinedFunctions(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading UserDefinedFunctions. collectionLink [{}]", collectionLink); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); return new FeedResponse<UserDefinedFunction>(new QueryIterable<UserDefinedFunction>(this, ResourceType.UserDefinedFunction, UserDefinedFunction.class, path, options)); }
private long getCountValue(SqlQuerySpec querySpec, boolean isCrossPartitionQuery, String collectionName) { final FeedResponse<Document> feedResponse = executeQuery(querySpec, isCrossPartitionQuery, collectionName); final Object value = feedResponse.getQueryIterable().toList().get(0).getHashMap().get(COUNT_VALUE_KEY); if (value instanceof Integer) { return Long.valueOf((Integer) value); } else if (value instanceof Long) { return (Long) value; } else { throw new IllegalStateException("Unexpected value type " + value.getClass() + " of value: " + value); } }
/** * Reads all attachments in a document. * * @param documentLink the document link. * @param options the feed options. * @return the feed response with the read attachments. */ public FeedResponse<Attachment> readAttachments(String documentLink, FeedOptions options) { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading Attachments. attachmentLink [{}]", documentLink); String path = Utils.joinPath(documentLink, Paths.ATTACHMENTS_PATH_SEGMENT); return new FeedResponse<Attachment>(new QueryIterable<Attachment>(this, ResourceType.Attachment, Attachment.class, path, options)); }
/** * Query for aggregation values in a document collection. * * @param collectionLink the link to the parent document collection. * @param querySpec the SQL query specification. * @param feedOptions the feed options. * @param partitionKey the partitionKey. * @return a list containing the aggregation values */ public List<Object> queryAggregateValues(String collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions, Object partitionKey) { List<Document> items = this.queryDocuments(collectionLink, querySpec, feedOptions, partitionKey) .getQueryIterable().toList(); List<Object> values = new ArrayList<>(items.size()); for (Document item : items) { if (item.propertyBag.length() > 0) { values.add(item.propertyBag.get(item.propertyBag.keys().next().toString())); } else { values.add(null); } } return values; }
/** * Reads all permissions. * * @param userLink the user link. * @param options the feed options. * @return the feed response with the read permissions. */ public FeedResponse<Permission> readPermissions(String userLink, FeedOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading Permissions. permissionLink [{}]", userLink); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); return new FeedResponse<Permission>(new QueryIterable<Permission>(this, ResourceType.Permission, Permission.class, path, options)); }
private <T> List<T> executeQuery(@NonNull SqlQuerySpec sqlQuerySpec, boolean isCrossPartition, @NonNull Class<T> domainClass, String collectionName) { final FeedResponse<Document> feedResponse = executeQuery(sqlQuerySpec, isCrossPartition, collectionName); final List<Document> result = feedResponse.getQueryIterable().toList(); return result.stream().map(r -> getConverter().read(domainClass, r)).collect(Collectors.toList()); }
/** * Reads all document collections in a database. * * @param databaseLink the database link. * @param options the fee options. * @return the feed response with the read collections. */ public FeedResponse<DocumentCollection> readCollections(String databaseLink, FeedOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading Collections. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); return new FeedResponse<DocumentCollection>(new QueryIterable<DocumentCollection>(this, ResourceType.DocumentCollection, DocumentCollection.class, path, options)); }
public <T> List<T> findAll(String collectionName, final Class<T> entityClass) { final List<DocumentCollection> collections = documentDbFactory.getDocumentClient(). queryCollections( getDatabaseLink(this.databaseName), new SqlQuerySpec("SELECT * FROM ROOT r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", collectionName))), null) .getQueryIterable().toList(); if (collections.size() != 1) { throw new RuntimeException("expect only one collection: " + collectionName + " in database: " + this.databaseName + ", but found " + collections.size()); } final List<Document> results = documentDbFactory.getDocumentClient() .queryDocuments(collections.get(0).getSelfLink(), "SELECT * FROM c", null) .getQueryIterable().toList(); final List<T> entities = new ArrayList<>(); for (int i = 0; i < results.size(); i++) { final T entity = mappingDocumentDbConverter.read(entityClass, results.get(i)); entities.add(entity); } return entities; }
/** * Reads all documents in a document collection. * * @param collectionLink the collection link. * @param options the feed options. * @return the feed response with read documents. */ public FeedResponse<Document> readDocuments(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading Documents. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, Paths.DOCUMENTS_PATH_SEGMENT); return new FeedResponse<Document>(new QueryIterable<Document>(this, ResourceType.Document, Document.class, path, options)); }
public <T> List<T> find(Query query, Class<T> domainClass, String collectionName) { final SqlQuerySpec sqlQuerySpec = createSqlQuerySpec(query, domainClass); // TODO (wepa) Collection link should be created locally without accessing database, // but currently exception will be thrown if not fetching collection url from database. // Run repository integration test to reproduce. final DocumentCollection collection = getDocCollection(collectionName); final FeedOptions feedOptions = new FeedOptions(); final Optional<Object> partitionKeyValue = getPartitionKeyValue(query, domainClass); if (!partitionKeyValue.isPresent()) { feedOptions.setEnableCrossPartitionQuery(true); } final List<Document> results = documentDbFactory.getDocumentClient() .queryDocuments(collection.getSelfLink(), sqlQuerySpec, feedOptions) .getQueryIterable().toList(); final List<T> entities = new ArrayList<>(); for (int i = 0; i < results.size(); i++) { final T entity = mappingDocumentDbConverter.read(domainClass, results.get(i)); entities.add(entity); } return entities; }