From 17593baf9e9a1cc9f3a45ebff7326af86199cf5f Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Mon, 9 Mar 2020 17:45:41 -0700 Subject: [PATCH 01/11] Fresh start --- .gitignore | 51 --- CODE_OF_CONDUCT.md | 9 - LICENSE | 21 - README.md | 101 ----- SECURITY.md | 41 -- pom.xml | 83 ---- .../changefeed/SampleChangeFeedProcessor.java | 270 ------------- .../changefeed/SampleConfigurations.java | 36 -- .../examples/common/AccountSettings.java | 40 -- .../azure/cosmos/examples/common/Address.java | 35 -- .../azure/cosmos/examples/common/Child.java | 53 --- .../cosmos/examples/common/CustomPOJO.java | 21 - .../cosmos/examples/common/Families.java | 117 ------ .../azure/cosmos/examples/common/Family.java | 74 ---- .../azure/cosmos/examples/common/Parent.java | 33 -- .../com/azure/cosmos/examples/common/Pet.java | 16 - .../async/SampleCRUDQuickstartAsync.java | 342 ---------------- .../sync/SampleCRUDQuickstart.java | 251 ------------ .../async/SampleIndexManagementAsync.java | 368 ------------------ .../sync/SampleIndexManagement.java | 273 ------------- .../async/SampleStoredProcedureAsync.java | 207 ---------- .../sync/SampleStoredProcedure.java | 174 --------- src/main/resources/log4j2.properties | 21 - .../multi-master-sample-config.properties | 8 - src/main/resources/resolver-storedproc.txt | 45 --- 25 files changed, 2690 deletions(-) delete mode 100644 .gitignore delete mode 100644 CODE_OF_CONDUCT.md delete mode 100644 LICENSE delete mode 100644 README.md delete mode 100644 SECURITY.md delete mode 100644 pom.xml delete mode 100644 src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java delete mode 100644 src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java delete mode 100644 src/main/java/com/azure/cosmos/examples/common/AccountSettings.java delete mode 100644 src/main/java/com/azure/cosmos/examples/common/Address.java delete mode 100644 src/main/java/com/azure/cosmos/examples/common/Child.java delete mode 100644 src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java delete mode 100644 src/main/java/com/azure/cosmos/examples/common/Families.java delete mode 100644 src/main/java/com/azure/cosmos/examples/common/Family.java delete mode 100644 src/main/java/com/azure/cosmos/examples/common/Parent.java delete mode 100644 src/main/java/com/azure/cosmos/examples/common/Pet.java delete mode 100644 src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java delete mode 100644 src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java delete mode 100644 src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java delete mode 100644 src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java delete mode 100644 src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java delete mode 100644 src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java delete mode 100644 src/main/resources/log4j2.properties delete mode 100644 src/main/resources/multi-master-sample-config.properties delete mode 100644 src/main/resources/resolver-storedproc.txt diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 00a9c64..0000000 --- a/.gitignore +++ /dev/null @@ -1,51 +0,0 @@ -target/ -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next -release.properties -dependency-reduced-pom.xml -buildNumber.properties -.mvn/timing.properties -# https://github.com/takari/maven-wrapper#usage-without-binary-jar -.mvn/wrapper/maven-wrapper.jar - -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# idea files -/.idea/ - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Eclipse project file -*.project - -# Maven autogenerated classpath -*.classpath - -#VSCode Directories -/*.settings/ -/*.vscode/ -/target/ - -*.iml diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index c72a574..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,9 +0,0 @@ -# Microsoft Open Source Code of Conduct - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). - -Resources: - -- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) -- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) -- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 3d8b93b..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ - MIT License - - Copyright (c) Microsoft Corporation. - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE diff --git a/README.md b/README.md deleted file mode 100644 index 829a2ee..0000000 --- a/README.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -page_type: sample -languages: -- java -products: -- java sdk -description: "Sample code repo for Azure Cosmos DB Java SDK for SQL API" -urlFragment: "" ---- - -# Azure Cosmos DB Java SQL API Samples - - - -Sample code repo for Azure Cosmos DB Java SDK for SQL API. By cloning and running these samples, and then studying their implementations, you will have an example for sending various requests to Azure Cosmos DB from Java SDK via the SQL API. - -## Contents - -| File/folder | Description | -|-------------------|--------------------------------------------| -| `src` | Java sample source code. Many samples have 'sync' and 'async' variants | -| `.gitignore` | Define what to ignore at commit time. | -| `CHANGELOG.md` | List of changes to the sample. | -| `CONTRIBUTING.md` | Guidelines for contributing to the sample. | -| `README.md` | This README file. | -| `LICENSE` | The license for the sample. | -| `pom.xml` | Maven Project Object Model File - -## Prerequisites - -* A Java IDE such as IntelliJ IDEA or VSCode -* Maven -* Java SE JRE 8 -* Setting up an Azure Cosmos DB account through the Azure Portal. The **Create a database account** section of [this guide](https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-java) walks you through account creation. -* The hostname and master key for your Azure Cosmos DB account - -## Setup - -Clone the sample to your PC. Using your Java IDE, open pom.xml as a Maven project. - -## Running the sample - -*If you are using Intellij IDEA as your Java IDE:* Once you have opened the project, go to the **Run/Debug Configurations** drop-down and choose **Edit Configurations**. -In the **Edit Configurations** dialog, click the **+** (**Add New Configuration**) button, select **Application** as the configuration type, - and give the new configuration a name. Once you are looking at the settings for your new Configuration, find **Environment variables** and paste - -``` -ACCOUNT_HOST=your account hostname;ACCOUNT_KEY=your account master key -``` - -which gives the sample read/write access to your account. - -To choose which sample will run, populate the **Main class** field of the Configuration with - -``` -com.azure.cosmos.examples.changefeed.sample -``` - -where *sample* can be -* SampleCRUDQuickstart -* SampleCRUDQuickstartAsync -* SampleIndexManagement -* SampleIndexManagementAsync -* SampleStoredProcedure -* SampleStoredProcedureAsync -* SampleChangeFeedProcessor - -*Build and execute from command line without an IDE:* From top-level directory of repo: -``` -mvn clean package -mvn exec:java -Dexec.mainClass="com.azure.cosmos.examples.changefeed.sample" -DACCOUNT_HOST=your account hostname -DACCOUNT_KEY=your account master key -``` - -where *sample*, *your account hostname*, and *your account master key* are to be filled in as above. This will rebuild and run the selected sample. - -## Key concepts - -These samples cover a range of Azure Cosmos DB usage topics from more to less basic: -* Basic management of databases, containers and items -* Indexing, stored procedures -* Change Feed - -## Contributing - -This project welcomes contributions and suggestions. Most contributions require you to agree to a -Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us -the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. - -When you submit a pull request, a CLA bot will automatically determine whether you need to provide -a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions -provided by the bot. You will only need to do this once across all repos using our CLA. - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or -contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index 7ab49eb..0000000 --- a/SECURITY.md +++ /dev/null @@ -1,41 +0,0 @@ - - -## Security - -Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). - -If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)) of a security vulnerability, please report it to us as described below. - -## Reporting Security Issues - -**Please do not report security vulnerabilities through public GitHub issues.** - -Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). - -If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc). - -You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). - -Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: - - * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) - * Full paths of source file(s) related to the manifestation of the issue - * The location of the affected source code (tag/branch/commit or direct URL) - * Any special configuration required to reproduce the issue - * Step-by-step instructions to reproduce the issue - * Proof-of-concept or exploit code (if possible) - * Impact of the issue, including how an attacker might exploit the issue - -This information will help us triage your report more quickly. - -If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. - -## Preferred Languages - -We prefer all communications to be in English. - -## Policy - -Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). - - diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 57eb621..0000000 --- a/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - 4.0.0 - - com.azure - azure-cosmos-java-sql-api-samples - 1.0-SNAPSHOT - Get Started With Sync / Async Java SDK for SQL API of Azure Cosmos DB Database Service - - UTF-8 - - - - azure-sdk-for-java - https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 - - - - - azure-sdk-for-java - https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 - - true - - - true - - - - - - - - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - - sync - - com.azure.cosmos.sample.sync.SyncMain - - - - async - - com.azure.cosmos.sample.async.AsyncMain - - - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - - - org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 - - - - - - - - - com.azure - azure-cosmos - 4.0.0-preview.2 - - - \ No newline at end of file diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java deleted file mode 100644 index c83cb82..0000000 --- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java +++ /dev/null @@ -1,270 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.cosmos.examples.changefeed; - -import com.azure.cosmos.ChangeFeedProcessor; -import com.azure.cosmos.ConnectionPolicy; -import com.azure.cosmos.ConsistencyLevel; -import com.azure.cosmos.CosmosAsyncContainer; -import com.azure.cosmos.CosmosAsyncContainerResponse; -import com.azure.cosmos.CosmosAsyncDatabase; -import com.azure.cosmos.CosmosClientBuilder; -import com.azure.cosmos.CosmosClientException; -import com.azure.cosmos.CosmosContainerProperties; -import com.azure.cosmos.CosmosContainerRequestOptions; -import com.azure.cosmos.CosmosAsyncClient; -import com.azure.cosmos.examples.common.CustomPOJO; -import com.azure.cosmos.implementation.Utils; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang3.RandomStringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import reactor.core.scheduler.Schedulers; - -import java.time.Duration; -import java.util.List; - -/** - * Sample for Change Feed Processor. - * - */ -public class SampleChangeFeedProcessor { - - public static int WAIT_FOR_WORK = 60000; - public static final String DATABASE_NAME = "db_" + RandomStringUtils.randomAlphabetic(7); - public static final String COLLECTION_NAME = "coll_" + RandomStringUtils.randomAlphabetic(7); - private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper(); - protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); - - - private static ChangeFeedProcessor changeFeedProcessorInstance; - private static boolean isWorkCompleted = false; - - public static void main (String[]args) { - logger.info("BEGIN Sample"); - - try { - //This sample models an application where documents are being inserted into one container (the "feed container"), - //and meanwhile another worker thread or worker application is pulling inserted documents from the feed container's Change Feed - //and operating on them in some way. For one or more workers to process the Change Feed of a container, the workers must first contact the server - //and "lease" access to monitor one or more partitions of the feed container. The Change Feed Processor Library - //handles leasing automatically for you, however you must create a separate "lease container" where the Change Feed - //Processor Library can store and track leases container partitions. - - //Summary of the next four commands: - //-Create an asynchronous Azure Cosmos DB client and database so that we can issue async requests to the DB - //-Create a "feed container" and a "lease container" in the DB - System.out.println("-->CREATE DocumentClient"); - CosmosAsyncClient client = getCosmosClient(); - - System.out.println("-->CREATE sample's database: " + DATABASE_NAME); - CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME); - - System.out.println("-->CREATE container for documents: " + COLLECTION_NAME); - CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME); - - System.out.println("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); - CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); - - //Model of a worker thread or application which leases access to monitor one or more feed container - //partitions via the Change Feed. In a real-world application you might deploy this code in an Azure function. - //The next line causes the worker to create and start an instance of the Change Feed Processor. See the implementation of getChangeFeedProcessor() for guidance - //on creating a handler for Change Feed events. In this stream, we also trigger the insertion of 10 documents on a separate - //thread. - System.out.println("-->START Change Feed Processor on worker (handles changes asynchronously)"); - changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); - changeFeedProcessorInstance.start() - .subscribeOn(Schedulers.elastic()) - .doOnSuccess(aVoid -> { - //pass - }) - .subscribe(); - - //These two lines model an application which is inserting ten documents into the feed container - System.out.println("-->START application that inserts documents into feed container"); - createNewDocumentsCustomPOJO(feedContainer, 10, Duration.ofSeconds(3)); - isWorkCompleted = true; - - //This loop models the Worker main loop, which spins while its Change Feed Processor instance asynchronously - //handles incoming Change Feed events from the feed container. Of course in this sample, polling - //isWorkCompleted is unnecessary because items are being added to the feed container on the same thread, and you - //can see just above isWorkCompleted is set to true. - //But conceptually the worker is part of a different thread or application than the one which is inserting - //into the feed container; so this code illustrates the worker waiting and listening for changes to the feed container - long remainingWork = WAIT_FOR_WORK; - while (!isWorkCompleted && remainingWork > 0) { - Thread.sleep(100); - remainingWork -= 100; - } - - //When all documents have been processed, clean up - if (isWorkCompleted) { - if (changeFeedProcessorInstance != null) { - changeFeedProcessorInstance.stop().subscribe(); - } - } else { - throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); - } - - System.out.println("-->DELETE sample's database: " + DATABASE_NAME); - deleteDatabase(cosmosDatabase); - - Thread.sleep(500); - - } catch (Exception e) { - e.printStackTrace(); - } - - System.out.println("END Sample"); - } - - public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosAsyncContainer feedContainer, CosmosAsyncContainer leaseContainer) { - return ChangeFeedProcessor.changeFeedProcessorBuilder() - .setHostName(hostName) - .setFeedContainer(feedContainer) - .setLeaseContainer(leaseContainer) - .setHandleChanges((List docs) -> { - System.out.println("--->setHandleChanges() START"); - - for (JsonNode document : docs) { - try { - //Change Feed hands the document to you in the form of a JsonNode - //As a developer you have two options for handling the JsonNode document provided to you by Change Feed - //One option is to operate on the document in the form of a JsonNode, as shown below. This is great - //especially if you do not have a single uniform data model for all documents. - System.out.println("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() - .writeValueAsString(document)); - - //You can also transform the JsonNode to a POJO having the same structure as the JsonNode, - //as shown below. Then you can operate on the POJO. - CustomPOJO pojo_doc = OBJECT_MAPPER.treeToValue(document, CustomPOJO.class); - System.out.println("----=>id: " + pojo_doc.getId()); - - } catch (JsonProcessingException e) { - e.printStackTrace(); - } - } - System.out.println("--->handleChanges() END"); - - }) - .build(); - } - - public static CosmosAsyncClient getCosmosClient() { - - return new CosmosClientBuilder() - .setEndpoint(SampleConfigurations.HOST) - .setKey(SampleConfigurations.MASTER_KEY) - .setConnectionPolicy(ConnectionPolicy.getDefaultPolicy()) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildAsyncClient(); - } - - public static CosmosAsyncDatabase createNewDatabase(CosmosAsyncClient client, String databaseName) { - return client.createDatabaseIfNotExists(databaseName).block().getDatabase(); - } - - public static void deleteDatabase(CosmosAsyncDatabase cosmosDatabase) { - cosmosDatabase.delete().block(); - } - - public static CosmosAsyncContainer createNewCollection(CosmosAsyncClient client, String databaseName, String collectionName) { - CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); - CosmosAsyncContainer collectionLink = databaseLink.getContainer(collectionName); - CosmosAsyncContainerResponse containerResponse = null; - - try { - containerResponse = collectionLink.read().block(); - - if (containerResponse != null) { - throw new IllegalArgumentException(String.format("Collection %s already exists in database %s.", collectionName, databaseName)); - } - } catch (RuntimeException ex) { - if (ex instanceof CosmosClientException) { - CosmosClientException cosmosClientException = (CosmosClientException) ex; - - if (cosmosClientException.getStatusCode() != 404) { - throw ex; - } - } else { - throw ex; - } - } - - CosmosContainerProperties containerSettings = new CosmosContainerProperties(collectionName, "/id"); - CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); - containerResponse = databaseLink.createContainer(containerSettings, 10000, requestOptions).block(); - - if (containerResponse == null) { - throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName)); - } - - return containerResponse.getContainer(); - } - - public static CosmosAsyncContainer createNewLeaseCollection(CosmosAsyncClient client, String databaseName, String leaseCollectionName) { - CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); - CosmosAsyncContainer leaseCollectionLink = databaseLink.getContainer(leaseCollectionName); - CosmosAsyncContainerResponse leaseContainerResponse = null; - - try { - leaseContainerResponse = leaseCollectionLink.read().block(); - - if (leaseContainerResponse != null) { - leaseCollectionLink.delete().block(); - - try { - Thread.sleep(1000); - } catch (InterruptedException ex) { - ex.printStackTrace(); - } - } - } catch (RuntimeException ex) { - if (ex instanceof CosmosClientException) { - CosmosClientException cosmosClientException = (CosmosClientException) ex; - - if (cosmosClientException.getStatusCode() != 404) { - throw ex; - } - } else { - throw ex; - } - } - - CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id"); - CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); - - leaseContainerResponse = databaseLink.createContainer(containerSettings, 400,requestOptions).block(); - - if (leaseContainerResponse == null) { - throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); - } - - return leaseContainerResponse.getContainer(); - } - - public static void createNewDocumentsCustomPOJO(CosmosAsyncContainer containerClient, int count, Duration delay) { - String suffix = RandomStringUtils.randomAlphabetic(10); - for (int i = 0; i <= count; i++) { - CustomPOJO document = new CustomPOJO(); - document.setId(String.format("0%d-%s", i, suffix)); - - containerClient.createItem(document).subscribe(doc -> { - System.out.println("---->DOCUMENT WRITE: " + doc); - }); - - long remainingWork = delay.toMillis(); - try { - while (remainingWork > 0) { - Thread.sleep(100); - remainingWork -= 100; - } - } catch (InterruptedException iex) { - // exception caught - break; - } - } - } -} diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java deleted file mode 100644 index 86e75c7..0000000 --- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.cosmos.examples.changefeed; - -import com.google.common.base.Strings; -import org.apache.commons.lang3.StringUtils; - -/** - * Contains the configurations for tests. - *

- * For running tests, you can pass a customized endpoint configuration in one of the following - * ways: - *

- *

- * If none of the above is set, emulator endpoint will be used. - */ -public final class SampleConfigurations { - // REPLACE MASTER_KEY and HOST with values from your Azure Cosmos DB account. - // The default values are credentials of the local emulator, which are not used in any production environment. - // - public static String MASTER_KEY = - System.getProperty("ACCOUNT_KEY", - StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("ACCOUNT_KEY")), - "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")); - - public static String HOST = - System.getProperty("ACCOUNT_HOST", - StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("ACCOUNT_HOST")), - "https://localhost:8081/")); -} diff --git a/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java b/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java deleted file mode 100644 index 12bb3ba..0000000 --- a/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.common; - -import org.apache.commons.lang3.StringUtils; - -/** - * Contains the account configurations for Sample. - * - * For running tests, you can pass a customized endpoint configuration in one of the following - * ways: - *

- * - * If none of the above is set, emulator endpoint will be used. - * Emulator http cert is self signed. If you are using emulator, - * make sure emulator https certificate is imported - * to java trusted cert store: - * https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator-export-ssl-certificates - */ -public class AccountSettings { - // Replace MASTER_KEY and HOST with values from your Azure Cosmos DB account. - // The default values are credentials of the local emulator, which are not used in any production environment. - // - public static String MASTER_KEY = - System.getProperty("ACCOUNT_KEY", - StringUtils.defaultString(StringUtils.trimToNull( - System.getenv().get("ACCOUNT_KEY")), - "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")); - - public static String HOST = - System.getProperty("ACCOUNT_HOST", - StringUtils.defaultString(StringUtils.trimToNull( - System.getenv().get("ACCOUNT_HOST")), - "https://localhost:443/")); -} diff --git a/src/main/java/com/azure/cosmos/examples/common/Address.java b/src/main/java/com/azure/cosmos/examples/common/Address.java deleted file mode 100644 index ec7d5b3..0000000 --- a/src/main/java/com/azure/cosmos/examples/common/Address.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.common; - -public class Address { - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getCounty() { - return county; - } - - public void setCounty(String county) { - this.county = county; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - private String state; - private String county; - private String city; -} - diff --git a/src/main/java/com/azure/cosmos/examples/common/Child.java b/src/main/java/com/azure/cosmos/examples/common/Child.java deleted file mode 100644 index 98cdd5c..0000000 --- a/src/main/java/com/azure/cosmos/examples/common/Child.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.common; - -public class Child { - public String getFamilyName() { - return familyName; - } - - public void setFamilyName(String familyName) { - this.familyName = familyName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public int getGrade() { - return grade; - } - - public void setGrade(int grade) { - this.grade = grade; - } - - public Pet[] getPets() { - return pets; - } - - public void setPets(Pet[] pets) { - this.pets = pets; - } - - private String familyName; - private String firstName; - private String gender; - private int grade; - private Pet[] pets; -} - diff --git a/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java b/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java deleted file mode 100644 index 7704081..0000000 --- a/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.azure.cosmos.examples.common; - -public class CustomPOJO { - private String id; - - public CustomPOJO() { - - } - - public CustomPOJO(String id) { - this.id=id; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } -} diff --git a/src/main/java/com/azure/cosmos/examples/common/Families.java b/src/main/java/com/azure/cosmos/examples/common/Families.java deleted file mode 100644 index fd549ee..0000000 --- a/src/main/java/com/azure/cosmos/examples/common/Families.java +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.common; - -public class Families { - - public static Family getAndersenFamilyItem() { - Family andersenFamily = new Family(); - andersenFamily.setId("Andersen-" + System.currentTimeMillis()); - andersenFamily.setLastName("Andersen"); - - Parent parent1 = new Parent(); - parent1.setFirstName("Thomas"); - - Parent parent2 = new Parent(); - parent2.setFirstName("Mary Kay"); - - andersenFamily.setParents(new Parent[] { parent1, parent2 }); - - Child child1 = new Child(); - child1.setFirstName("Henriette Thaulow"); - child1.setGender("female"); - child1.setGrade(5); - - Pet pet1 = new Pet(); - pet1.setGivenName("Fluffy"); - - child1.setPets(new Pet[] { pet1 }); - - andersenFamily.setDistrict("WA5"); - Address address = new Address(); - address.setCity("Seattle"); - address.setCounty("King"); - address.setState("WA"); - - andersenFamily.setAddress(address); - andersenFamily.setRegistered(true); - - return andersenFamily; - } - - public static Family getWakefieldFamilyItem() { - Family wakefieldFamily = new Family(); - wakefieldFamily.setId("Wakefield-" + System.currentTimeMillis()); - wakefieldFamily.setLastName("Wakefield"); - - Parent parent1 = new Parent(); - parent1.setFamilyName("Wakefield"); - parent1.setFirstName("Robin"); - - Parent parent2 = new Parent(); - parent2.setFamilyName("Miller"); - parent2.setFirstName("Ben"); - - wakefieldFamily.setParents(new Parent[] { parent1, parent2 }); - - Child child1 = new Child(); - child1.setFirstName("Jesse"); - child1.setFamilyName("Merriam"); - child1.setGrade(8); - - Pet pet1 = new Pet(); - pet1.setGivenName("Goofy"); - - Pet pet2 = new Pet(); - pet2.setGivenName("Shadow"); - - child1.setPets(new Pet[] { pet1, pet2 }); - - Child child2 = new Child(); - child2.setFirstName("Lisa"); - child2.setFamilyName("Miller"); - child2.setGrade(1); - child2.setGender("female"); - - wakefieldFamily.setChildren(new Child[] { child1, child2 }); - - Address address = new Address(); - address.setCity("NY"); - address.setCounty("Manhattan"); - address.setState("NY"); - - wakefieldFamily.setAddress(address); - wakefieldFamily.setDistrict("NY23"); - wakefieldFamily.setRegistered(true); - return wakefieldFamily; - } - - public static Family getJohnsonFamilyItem() { - Family andersenFamily = new Family(); - andersenFamily.setId("Johnson-" + System.currentTimeMillis()); - andersenFamily.setLastName("Johnson"); - - Parent parent1 = new Parent(); - parent1.setFirstName("John"); - - Parent parent2 = new Parent(); - parent2.setFirstName("Lili"); - - return andersenFamily; - } - - public static Family getSmithFamilyItem() { - Family andersenFamily = new Family(); - andersenFamily.setId("Smith-" + System.currentTimeMillis()); - andersenFamily.setLastName("Smith"); - - Parent parent1 = new Parent(); - parent1.setFirstName("John"); - - Parent parent2 = new Parent(); - parent2.setFirstName("Cynthia"); - - return andersenFamily; - } -} diff --git a/src/main/java/com/azure/cosmos/examples/common/Family.java b/src/main/java/com/azure/cosmos/examples/common/Family.java deleted file mode 100644 index 4e337b3..0000000 --- a/src/main/java/com/azure/cosmos/examples/common/Family.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.common; - -public class Family { - public Family() { - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getDistrict() { - return district; - } - - public void setDistrict(String district) { - this.district = district; - } - - public Parent[] getParents() { - return parents; - } - - public void setParents(Parent[] parents) { - this.parents = parents; - } - - public Child[] getChildren() { - return children; - } - - public void setChildren(Child[] children) { - this.children = children; - } - - public Address getAddress() { - return address; - } - - public void setAddress(Address address) { - this.address = address; - } - - public boolean isRegistered() { - return isRegistered; - } - - public void setRegistered(boolean isRegistered) { - this.isRegistered = isRegistered; - } - - private String id; - private String lastName; - private String district; - private Parent[] parents; - private Child[] children; - private Address address; - private boolean isRegistered; -} - diff --git a/src/main/java/com/azure/cosmos/examples/common/Parent.java b/src/main/java/com/azure/cosmos/examples/common/Parent.java deleted file mode 100644 index d7753a8..0000000 --- a/src/main/java/com/azure/cosmos/examples/common/Parent.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.common; - -public class Parent { - - public Parent() { - } - - public Parent(String firstName) { - this.firstName = firstName; - } - - public String getFamilyName() { - return familyName; - } - - public void setFamilyName(String familyName) { - this.familyName = familyName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - private String familyName; - private String firstName; -} diff --git a/src/main/java/com/azure/cosmos/examples/common/Pet.java b/src/main/java/com/azure/cosmos/examples/common/Pet.java deleted file mode 100644 index 062ce93..0000000 --- a/src/main/java/com/azure/cosmos/examples/common/Pet.java +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.common; - -public class Pet { - public String getGivenName() { - return givenName; - } - - public void setGivenName(String givenName) { - this.givenName = givenName; - } - - private String givenName; -} diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java deleted file mode 100644 index 3e5b581..0000000 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java +++ /dev/null @@ -1,342 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.crudquickstart.async; - - -import com.azure.cosmos.*; -import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; -import com.azure.cosmos.examples.common.AccountSettings; -import com.azure.cosmos.examples.common.Families; -import com.azure.cosmos.examples.common.Family; -import com.google.common.collect.Lists; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.time.Duration; -import java.util.concurrent.CountDownLatch; -import java.util.stream.Collectors; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SampleCRUDQuickstartAsync { - - private CosmosAsyncClient client; - - private final String databaseName = "AzureSampleFamilyDB"; - private final String containerName = "FamilyContainer"; - - private CosmosAsyncDatabase database; - private CosmosAsyncContainer container; - - protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); - - public void close() { - client.close(); - } - - /** - * Run a Hello CosmosDB console application. - * - * @param args command line args. - */ - //
- public static void main(String[] args) { - SampleCRUDQuickstartAsync p = new SampleCRUDQuickstartAsync(); - - try { - System.out.println("Starting ASYNC main"); - p.getStartedDemo(); - System.out.println("Demo complete, please hold while resources are released"); - } catch (Exception e) { - e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); - } finally { - System.out.println("Closing the client"); - p.shutdown(); - } - } - - //
- - private void getStartedDemo() throws Exception { - //This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations - //with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will - //1. Create asynchronous client, database and container instances - //2. Create several items - //3. Upsert one of the items - //4. Perform a query over the items - //5. Delete an item - //6. Delete the Cosmos DB database and container resources and close the client. - - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); - - ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); - // Setting the preferred location to Cosmos DB Account region - // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application - defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); - - // Create async client - // - client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildAsyncClient(); - - // - - createDatabaseIfNotExists(); - createContainerIfNotExists(); - - Family andersenFamilyItem=Families.getAndersenFamilyItem(); - Family wakefieldFamilyItem=Families.getWakefieldFamilyItem(); - Family johnsonFamilyItem=Families.getJohnsonFamilyItem(); - Family smithFamilyItem=Families.getSmithFamilyItem(); - - // Setup family items to create - Flux familiesToCreate = Flux.just(andersenFamilyItem, - wakefieldFamilyItem, - johnsonFamilyItem, - smithFamilyItem); - - // Creates several items in the container - createFamilies(familiesToCreate); - - // Upsert one of the items in the container - upsertFamily(wakefieldFamilyItem); - - familiesToCreate = Flux.just(andersenFamilyItem, - wakefieldFamilyItem, - johnsonFamilyItem, - smithFamilyItem); - - System.out.println("Reading items."); - readItems(familiesToCreate); - - System.out.println("Querying items."); - queryItems(); - - System.out.println("Deleting an item."); - deleteItem(andersenFamilyItem); - } - - private void createDatabaseIfNotExists() throws Exception { - System.out.println("Create database " + databaseName + " if not exists."); - - // Create database if not exists - // - Mono databaseIfNotExists = client.createDatabaseIfNotExists(databaseName); - databaseIfNotExists.flatMap(databaseResponse -> { - database = databaseResponse.getDatabase(); - System.out.println("Checking database " + database.getId() + " completed!\n"); - return Mono.empty(); - }).block(); - // - } - - private void createContainerIfNotExists() throws Exception { - System.out.println("Create container " + containerName + " if not exists."); - - // Create container if not exists - // - - CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/lastName"); - Mono containerIfNotExists = database.createContainerIfNotExists(containerProperties, 400); - - // Create container with 400 RU/s - containerIfNotExists.flatMap(containerResponse -> { - container = containerResponse.getContainer(); - System.out.println("Checking container " + container.getId() + " completed!\n"); - return Mono.empty(); - }).block(); - - // - } - - private void createFamilies(Flux families) throws Exception { - - // - - final CountDownLatch completionLatch = new CountDownLatch(1); - - // Combine multiple item inserts, associated success println's, and a final aggregate stats println into one Reactive stream. - families.flatMap(family -> { - return container.createItem(family); - }) //Flux of item request responses - .flatMap(itemResponse -> { - System.out.println(String.format("Created item with request charge of %.2f within" + - " duration %s", - itemResponse.getRequestCharge(), itemResponse.getRequestLatency())); - System.out.println(String.format("Item ID: %s\n", itemResponse.getResource().getId())); - return Mono.just(itemResponse.getRequestCharge()); - }) //Flux of request charges - .reduce(0.0, - (charge_n,charge_nplus1) -> charge_n + charge_nplus1 - ) //Mono of total charge - there will be only one item in this stream - .subscribe(charge -> { - System.out.println(String.format("Created items with total request charge of %.2f\n", - charge)); - }, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.err.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} - ); //Preserve the total charge and print aggregate charge/item count stats. - - try { - completionLatch.await(); - } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); - } - - // - } - - private void upsertFamily(Family family_to_upsert) { - //Modify a field of the family object - System.out.println(String.format("Upserting the item with id %s after modifying the isRegistered field...",family_to_upsert.getId())); - family_to_upsert.setRegistered(!family_to_upsert.isRegistered()); - - //Upsert the modified item - Mono.just(family_to_upsert).flatMap(item -> { - CosmosAsyncItemResponse item_resp = container.upsertItem(family_to_upsert).block(); - - // Get upsert request charge and other properties like latency, and diagnostics strings, etc. - System.out.println(String.format("Upserted item with request charge of %.2f within duration %s", - item_resp.getRequestCharge(), item_resp.getRequestLatency())); - - return Mono.empty(); - }).subscribe(); - } - - private void readItems(Flux familiesToCreate) { - // Using partition key for point read scenarios. - // This will help fast look up of items because of partition key - // - - final CountDownLatch completionLatch = new CountDownLatch(1); - - familiesToCreate.flatMap(family -> { - Mono> asyncItemResponseMono = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); - return asyncItemResponseMono; - }) - .subscribe( - itemResponse -> { - double requestCharge = itemResponse.getRequestCharge(); - Duration requestLatency = itemResponse.getRequestLatency(); - System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", - itemResponse.getResource().getId(), requestCharge, requestLatency)); - }, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.err.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} - ); - - try { - completionLatch.await(); - } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); - } - - // - } - - private void queryItems() { - // - // Set some common query options - - FeedOptions queryOptions = new FeedOptions(); - queryOptions.maxItemCount(10); - //queryOptions.setEnableCrossPartitionQuery(true); //No longer needed in SDK v4 - // Set populate query metrics to get metrics around query executions - queryOptions.populateQueryMetrics(true); - - CosmosContinuablePagedFlux pagedFluxResponse = container.queryItems( - "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); - - final CountDownLatch completionLatch = new CountDownLatch(1); - - pagedFluxResponse.byPage().subscribe( - fluxResponse -> { - System.out.println("Got a page of query result with " + - fluxResponse.getResults().size() + " items(s)" - + " and request charge of " + fluxResponse.getRequestCharge()); - - System.out.println("Item Ids " + fluxResponse - .getResults() - .stream() - .map(Family::getId) - .collect(Collectors.toList())); - }, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.err.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} - ); - - try { - completionLatch.await(); - } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); - } - - // - } - - private void deleteItem(Family item) { - container.deleteItem(item.getId(),new PartitionKey(item.getLastName())).block(); - } - - private void shutdown() { - try { - //Clean shutdown - System.out.println("Deleting Cosmos DB resources"); - System.out.println("-Deleting container..."); - if (container != null) - container.delete().subscribe(); - System.out.println("-Deleting database..."); - if (database != null) - database.delete().subscribe(); - System.out.println("-Closing the client..."); - } catch (Exception err) { - System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); - err.printStackTrace(); - } - client.close(); - System.out.println("Done."); - } -} diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java deleted file mode 100644 index 293cd35..0000000 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.crudquickstart.sync; - -import com.azure.cosmos.ConnectionPolicy; -import com.azure.cosmos.ConsistencyLevel; -import com.azure.cosmos.CosmosClient; -import com.azure.cosmos.CosmosClientBuilder; -import com.azure.cosmos.CosmosClientException; -import com.azure.cosmos.CosmosContainer; -import com.azure.cosmos.CosmosContainerProperties; -import com.azure.cosmos.CosmosContinuablePagedIterable; -import com.azure.cosmos.CosmosDatabase; -import com.azure.cosmos.CosmosItemRequestOptions; -import com.azure.cosmos.CosmosItemResponse; -import com.azure.cosmos.FeedOptions; -import com.azure.cosmos.PartitionKey; -import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; -import com.azure.cosmos.examples.common.AccountSettings; -import com.azure.cosmos.examples.common.Families; -import com.azure.cosmos.examples.common.Family; -import com.google.common.collect.Lists; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SampleCRUDQuickstart { - - private CosmosClient client; - - private final String databaseName = "AzureSampleFamilyDB"; - private final String containerName = "FamilyContainer"; - - private CosmosDatabase database; - private CosmosContainer container; - - protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); - - public void close() { - client.close(); - } - - /** - * Run a Hello CosmosDB console application. - * - * @param args command line args. - */ - //
- public static void main(String[] args) { - SampleCRUDQuickstart p = new SampleCRUDQuickstart(); - - try { - System.out.println("Starting SYNC main"); - p.getStartedDemo(); - System.out.println("Demo complete, please hold while resources are released"); - } catch (Exception e) { - e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); - } finally { - System.out.println("Closing the client"); - p.shutdown(); - } - } - - //
- - private void getStartedDemo() throws Exception { - //This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations - //with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will - //1. Create synchronous client, database and container instances - //2. Create several items - //3. Upsert one of the items - //4. Perform a query over the items - //5. Delete an item - //6. Delete the Cosmos DB database and container resources and close the client. - - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); - - ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); - // Setting the preferred location to Cosmos DB Account region - // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application - defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); - - // Create sync client - // - client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildClient(); - - // - - createDatabaseIfNotExists(); - createContainerIfNotExists(); - - // Setup family items to create - ArrayList familiesToCreate = new ArrayList<>(); - familiesToCreate.add(Families.getAndersenFamilyItem()); - familiesToCreate.add(Families.getWakefieldFamilyItem()); - familiesToCreate.add(Families.getJohnsonFamilyItem()); - familiesToCreate.add(Families.getSmithFamilyItem()); - - // Creates several items in the container - // Also applies an upsert operation to one of the items (create if not present, otherwise replace) - createFamilies(familiesToCreate); - - System.out.println("Reading items."); - readItems(familiesToCreate); - - System.out.println("Querying items."); - queryItems(); - - System.out.println("Delete an item."); - deleteItem(familiesToCreate.get(0)); - } - - private void createDatabaseIfNotExists() throws Exception { - System.out.println("Create database " + databaseName + " if not exists."); - - // Create database if not exists - // - database = client.createDatabaseIfNotExists(databaseName).getDatabase(); - // - - System.out.println("Checking database " + database.getId() + " completed!\n"); - } - - private void createContainerIfNotExists() throws Exception { - System.out.println("Create container " + containerName + " if not exists."); - - // Create container if not exists - // - CosmosContainerProperties containerProperties = - new CosmosContainerProperties(containerName, "/lastName"); - - // Create container with 400 RU/s - container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); - // - - System.out.println("Checking container " + container.getId() + " completed!\n"); - } - - private void createFamilies(List families) throws Exception { - double totalRequestCharge = 0; - for (Family family : families) { - - // - // Create item using container that we created using sync client - - // Use lastName as partitionKey for cosmos item - // Using appropriate partition key improves the performance of database operations - CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); - CosmosItemResponse item = container.createItem(family, new PartitionKey(family.getLastName()), cosmosItemRequestOptions); - // - - // Get request charge and other properties like latency, and diagnostics strings, etc. - System.out.println(String.format("Created item with request charge of %.2f within duration %s", - item.getRequestCharge(), item.getRequestLatency())); - - totalRequestCharge += item.getRequestCharge(); - } - System.out.println(String.format("Created %d items with total request charge of %.2f", - families.size(), totalRequestCharge)); - - Family family_to_upsert = families.get(0); - System.out.println(String.format("Upserting the item with id %s after modifying the isRegistered field...",family_to_upsert.getId())); - family_to_upsert.setRegistered(!family_to_upsert.isRegistered()); - - CosmosItemResponse item = container.upsertItem(family_to_upsert); - - // Get upsert request charge and other properties like latency, and diagnostics strings, etc. - System.out.println(String.format("Upserted item with request charge of %.2f within duration %s", - item.getRequestCharge(), item.getRequestLatency())); - } - - private void readItems(ArrayList familiesToCreate) { - // Using partition key for point read scenarios. - // This will help fast look up of items because of partition key - familiesToCreate.forEach(family -> { - // - try { - CosmosItemResponse item = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); - double requestCharge = item.getRequestCharge(); - Duration requestLatency = item.getRequestLatency(); - System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", - item.getResource().getId(), requestCharge, requestLatency)); - } catch (CosmosClientException e) { - e.printStackTrace(); - System.out.println(String.format("Read Item failed with %s", e)); - } - // - }); - } - - private void queryItems() { - // - // Set some common query options - FeedOptions queryOptions = new FeedOptions(); - queryOptions.maxItemCount(10); - //queryOptions.setEnableCrossPartitionQuery(true); //No longer necessary in SDK v4 - // Set populate query metrics to get metrics around query executions - queryOptions.populateQueryMetrics(true); - - CosmosContinuablePagedIterable familiesPagedIterable = container.queryItems( - "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); - - familiesPagedIterable.iterableByPage().forEach(cosmosItemPropertiesFeedResponse -> { - System.out.println("Got a page of query result with " + - cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)" - + " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()); - - System.out.println("Item Ids " + cosmosItemPropertiesFeedResponse - .getResults() - .stream() - .map(Family::getId) - .collect(Collectors.toList())); - }); - // - } - - private void deleteItem(Family item) { - container.deleteItem(item.getId(),new PartitionKey(item.getLastName()),new CosmosItemRequestOptions()); - } - - private void shutdown() { - try { - //Clean shutdown - System.out.println("Deleting Cosmos DB resources"); - System.out.println("-Deleting container..."); - if (container != null) - container.delete(); - System.out.println("-Deleting database..."); - if (database != null) - database.delete(); - System.out.println("-Closing the client..."); - } catch (Exception err) { - System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); - err.printStackTrace(); - } - client.close(); - System.out.println("Done."); - } -} diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java deleted file mode 100644 index b335434..0000000 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java +++ /dev/null @@ -1,368 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.indexmanagement.async; - -import com.azure.cosmos.*; -import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; -import com.azure.cosmos.examples.common.AccountSettings; -import com.azure.cosmos.examples.common.Families; -import com.azure.cosmos.examples.common.Family; -import com.google.common.collect.Lists; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.stream.Collectors; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SampleIndexManagementAsync { - - private CosmosAsyncClient client; - - private final String databaseName = "AzureSampleFamilyDB"; - private final String containerName = "FamilyContainer"; - - private CosmosAsyncDatabase database; - private CosmosAsyncContainer container; - - protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); - - public void close() { - client.close(); - } - - /** - * Run a Hello CosmosDB console application. - * - * @param args command line args. - */ - //
- public static void main(String[] args) { - SampleIndexManagementAsync p = new SampleIndexManagementAsync(); - - try { - System.out.println("Starting ASYNC main"); - p.indexManagementDemo(); - System.out.println("Demo complete, please hold while resources are released"); - } catch (Exception e) { - e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); - } finally { - System.out.println("Closing the client"); - p.shutdown(); - } - } - - //
- - private void indexManagementDemo() throws Exception { - //This sample is similar to SampleCRUDQuickstartAsync, but modified to show indexing capabilities of Cosmos DB. - //Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of - //indexing capabilities. - - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); - - ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); - // Setting the preferred location to Cosmos DB Account region - // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application - defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); - - // Create async client - // - client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildAsyncClient(); - - // - - createDatabaseIfNotExists(); - - //Here is where index management is performed - createContainerIfNotExistsWithSpecifiedIndex(); - - Family andersenFamilyItem=Families.getAndersenFamilyItem(); - Family wakefieldFamilyItem=Families.getWakefieldFamilyItem(); - Family johnsonFamilyItem=Families.getJohnsonFamilyItem(); - Family smithFamilyItem=Families.getSmithFamilyItem(); - - // Setup family items to create - Flux familiesToCreate = Flux.just(andersenFamilyItem, - wakefieldFamilyItem, - johnsonFamilyItem, - smithFamilyItem); - - createFamilies(familiesToCreate); - - familiesToCreate = Flux.just(andersenFamilyItem, - wakefieldFamilyItem, - johnsonFamilyItem, - smithFamilyItem); - - System.out.println("Reading items."); - readItems(familiesToCreate); - - System.out.println("Querying items."); - queryItems(); - } - - private void createDatabaseIfNotExists() throws Exception { - System.out.println("Create database " + databaseName + " if not exists."); - - // Create database if not exists - // - Mono databaseIfNotExists = client.createDatabaseIfNotExists(databaseName); - databaseIfNotExists.flatMap(databaseResponse -> { - database = databaseResponse.getDatabase(); - System.out.println("Checking database " + database.getId() + " completed!\n"); - return Mono.empty(); - }).block(); - // - } - - private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception { - System.out.println("Create container " + containerName + " if not exists."); - - // Create container if not exists - // - - CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/lastName"); - - // - IndexingPolicy indexingPolicy = new IndexingPolicy(); - indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); //To turn indexing off set IndexingMode.NONE - - // Included paths - List includedPaths = new ArrayList<>(); - IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); - includedPaths.add(includedPath); - indexingPolicy.setIncludedPaths(includedPaths); - - // Excluded paths - List excludedPaths = new ArrayList<>(); - ExcludedPath excludedPath = new ExcludedPath(); - excludedPath.setPath("/name/*"); - excludedPaths.add(excludedPath); - indexingPolicy.setExcludedPaths(excludedPaths); - - // Spatial indices - if you need them, here is how to set them up: - /* - List spatialIndexes = new ArrayList(); - List collectionOfSpatialTypes = new ArrayList(); - - SpatialSpec spec = new SpatialSpec(); - spec.setPath("/locations/*"); - collectionOfSpatialTypes.add(SpatialType.Point); - spec.setSpatialTypes(collectionOfSpatialTypes); - spatialIndexes.add(spec); - - indexingPolicy.setSpatialIndexes(spatialIndexes); - */ - - // Composite indices - if you need them, here is how to set them up: - /* - List> compositeIndexes = new ArrayList<>(); - List compositePaths = new ArrayList<>(); - - CompositePath nameCompositePath = new CompositePath(); - nameCompositePath.setPath("/name"); - nameCompositePath.setOrder(CompositePathSortOrder.ASCENDING); - - CompositePath ageCompositePath = new CompositePath(); - ageCompositePath.setPath("/age"); - ageCompositePath.setOrder(CompositePathSortOrder.DESCENDING); - - compositePaths.add(ageCompositePath); - compositePaths.add(nameCompositePath); - - compositeIndexes.add(compositePaths); - indexingPolicy.setCompositeIndexes(compositeIndexes); - */ - - containerProperties.setIndexingPolicy(indexingPolicy); - - // - - Mono containerIfNotExists = database.createContainerIfNotExists(containerProperties, 400); - - // Create container with 400 RU/s - containerIfNotExists.flatMap(containerResponse -> { - container = containerResponse.getContainer(); - System.out.println("Checking container " + container.getId() + " completed!\n"); - return Mono.empty(); - }).block(); - - // - } - - private void createFamilies(Flux families) throws Exception { - - // - - final CountDownLatch completionLatch = new CountDownLatch(1); - - // Combine multiple item inserts, associated success println's, and a final aggregate stats println into one Reactive stream. - families.flatMap(family -> { - return container.createItem(family); - }) //Flux of item request responses - .flatMap(itemResponse -> { - System.out.println(String.format("Created item with request charge of %.2f within" + - " duration %s", - itemResponse.getRequestCharge(), itemResponse.getRequestLatency())); - System.out.println(String.format("Item ID: %s\n", itemResponse.getResource().getId())); - return Mono.just(itemResponse.getRequestCharge()); - }) //Flux of request charges - .reduce(0.0, - (charge_n,charge_nplus1) -> charge_n + charge_nplus1 - ) //Mono of total charge - there will be only one item in this stream - .subscribe(charge -> { - System.out.println(String.format("Created items with total request charge of %.2f\n", - charge)); - }, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.out.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} - ); //Preserve the total charge and print aggregate charge/item count stats. - - try { - completionLatch.await(); - } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); - } - - // - } - - private void readItems(Flux familiesToCreate) { - // Using partition key for point read scenarios. - // This will help fast look up of items because of partition key - // - - final CountDownLatch completionLatch = new CountDownLatch(1); - - familiesToCreate.flatMap(family -> { - Mono> asyncItemResponseMono = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); - return asyncItemResponseMono; - }) - .subscribe( - itemResponse -> { - double requestCharge = itemResponse.getRequestCharge(); - Duration requestLatency = itemResponse.getRequestLatency(); - System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", - itemResponse.getResource().getId(), requestCharge, requestLatency)); - }, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.out.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} - ); - - try { - completionLatch.await(); - } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); - } - - // - } - - private void queryItems() { - // - // Set some common query options - - FeedOptions queryOptions = new FeedOptions(); - queryOptions.maxItemCount(10); - // Set populate query metrics to get metrics around query executions - queryOptions.populateQueryMetrics(true); - - CosmosContinuablePagedFlux pagedFluxResponse = container.queryItems( - "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); - - final CountDownLatch completionLatch = new CountDownLatch(1); - - pagedFluxResponse.byPage().subscribe( - fluxResponse -> { - System.out.println("Got a page of query result with " + - fluxResponse.getResults().size() + " items(s)" - + " and request charge of " + fluxResponse.getRequestCharge()); - - System.out.println("Item Ids " + fluxResponse - .getResults() - .stream() - .map(Family::getId) - .collect(Collectors.toList())); - }, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.err.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} - ); - - try { - completionLatch.await(); - } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); - } - - // - } - - private void shutdown() { - try { - //Clean shutdown - System.out.println("Deleting Cosmos DB resources"); - System.out.println("-Deleting container..."); - if (container != null) - container.delete().subscribe(); - System.out.println("-Deleting database..."); - if (database != null) - database.delete().subscribe(); - System.out.println("-Closing the client..."); - } catch (Exception err) { - System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); - err.printStackTrace(); - } - client.close(); - System.out.println("Done."); - } -} diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java deleted file mode 100644 index fc07cab..0000000 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.indexmanagement.sync; - -import com.azure.cosmos.*; -import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; -import com.azure.cosmos.examples.common.AccountSettings; -import com.azure.cosmos.examples.common.Families; -import com.azure.cosmos.examples.common.Family; -import com.google.common.collect.Lists; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -public class SampleIndexManagement { - - private CosmosClient client; - - private final String databaseName = "AzureSampleFamilyDB"; - private final String containerName = "FamilyContainer"; - - private CosmosDatabase database; - private CosmosContainer container; - - protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); - - public void close() { - client.close(); - } - - /** - * Run a Hello CosmosDB console application. - * - * @param args command line args. - */ - //
- public static void main(String[] args) { - - SampleIndexManagement p = new SampleIndexManagement(); - - try { - System.out.println("Starting SYNC main"); - p.indexManagementDemo(); - System.out.println("Demo complete, please hold while resources are released"); - } catch (Exception e) { - e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); - } finally { - System.out.println("Closing the client"); - p.shutdown(); - } - } - - //
- - private void indexManagementDemo() throws Exception { - //This sample is similar to SampleCRUDQuickstart, but modified to show indexing capabilities of Cosmos DB. - //Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of - //indexing capabilities. - - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); - - ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); - // Setting the preferred location to Cosmos DB Account region - // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application - defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); - - // Create sync client - // - client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildClient(); - - // - - createDatabaseIfNotExists(); - - //Here is where index management is performed - createContainerIfNotExistsWithSpecifiedIndex(); - - // Setup family items to create - ArrayList familiesToCreate = new ArrayList<>(); - familiesToCreate.add(Families.getAndersenFamilyItem()); - familiesToCreate.add(Families.getWakefieldFamilyItem()); - familiesToCreate.add(Families.getJohnsonFamilyItem()); - familiesToCreate.add(Families.getSmithFamilyItem()); - - createFamilies(familiesToCreate); - - System.out.println("Reading items."); - readItems(familiesToCreate); - - System.out.println("Querying items."); - queryItems(); - } - - private void createDatabaseIfNotExists() throws Exception { - System.out.println("Create database " + databaseName + " if not exists."); - - // Create database if not exists - // - database = client.createDatabaseIfNotExists(databaseName).getDatabase(); - // - - System.out.println("Checking database " + database.getId() + " completed!\n"); - } - - private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception { - System.out.println("Create container " + containerName + " if not exists."); - - // Create container if not exists - CosmosContainerProperties containerProperties = - new CosmosContainerProperties(containerName, "/lastName"); - - // - IndexingPolicy indexingPolicy = new IndexingPolicy(); - indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); //To turn indexing off set IndexingMode.NONE - - // Included paths - List includedPaths = new ArrayList<>(); - IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); - includedPaths.add(includedPath); - indexingPolicy.setIncludedPaths(includedPaths); - - // Excluded paths - List excludedPaths = new ArrayList<>(); - ExcludedPath excludedPath = new ExcludedPath(); - excludedPath.setPath("/name/*"); - excludedPaths.add(excludedPath); - indexingPolicy.setExcludedPaths(excludedPaths); - - // Spatial indices - if you need them, here is how to set them up: - /* - List spatialIndexes = new ArrayList(); - List collectionOfSpatialTypes = new ArrayList(); - - SpatialSpec spec = new SpatialSpec(); - spec.setPath("/locations/*"); - collectionOfSpatialTypes.add(SpatialType.Point); - spec.setSpatialTypes(collectionOfSpatialTypes); - spatialIndexes.add(spec); - - indexingPolicy.setSpatialIndexes(spatialIndexes); - */ - - // Composite indices - if you need them, here is how to set them up: - /* - List> compositeIndexes = new ArrayList<>(); - List compositePaths = new ArrayList<>(); - - CompositePath nameCompositePath = new CompositePath(); - nameCompositePath.setPath("/name"); - nameCompositePath.setOrder(CompositePathSortOrder.ASCENDING); - - CompositePath ageCompositePath = new CompositePath(); - ageCompositePath.setPath("/age"); - ageCompositePath.setOrder(CompositePathSortOrder.DESCENDING); - - compositePaths.add(ageCompositePath); - compositePaths.add(nameCompositePath); - - compositeIndexes.add(compositePaths); - indexingPolicy.setCompositeIndexes(compositeIndexes); - */ - - containerProperties.setIndexingPolicy(indexingPolicy); - - // - - // Create container with 400 RU/s - container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); - - System.out.println("Checking container " + container.getId() + " completed!\n"); - } - - private void createFamilies(List families) throws Exception { - double totalRequestCharge = 0; - for (Family family : families) { - - // - // Create item using container that we created using sync client - - // Use lastName as partitionKey for cosmos item - // Using appropriate partition key improves the performance of database operations - CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); - CosmosItemResponse item = container.createItem(family, new PartitionKey(family.getLastName()), cosmosItemRequestOptions); - // - - // Get request charge and other properties like latency, and diagnostics strings, etc. - System.out.println(String.format("Created item with request charge of %.2f within" + - " duration %s", - item.getRequestCharge(), item.getRequestLatency())); - totalRequestCharge += item.getRequestCharge(); - } - System.out.println(String.format("Created %d items with total request " + - "charge of %.2f", - families.size(), - totalRequestCharge)); - } - - private void readItems(ArrayList familiesToCreate) { - // Using partition key for point read scenarios. - // This will help fast look up of items because of partition key - familiesToCreate.forEach(family -> { - // - try { - CosmosItemResponse item = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); - double requestCharge = item.getRequestCharge(); - Duration requestLatency = item.getRequestLatency(); - System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", - item.getResource().getId(), requestCharge, requestLatency)); - } catch (CosmosClientException e) { - e.printStackTrace(); - System.err.println(String.format("Read Item failed with %s", e)); - } - // - }); - } - - private void queryItems() { - // - // Set some common query options - FeedOptions queryOptions = new FeedOptions(); - queryOptions.maxItemCount(10); - // Set populate query metrics to get metrics around query executions - queryOptions.populateQueryMetrics(true); - - CosmosContinuablePagedIterable familiesPagedIterable = container.queryItems( - "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); - - familiesPagedIterable.iterableByPage().forEach(cosmosItemPropertiesFeedResponse -> { - System.out.println("Got a page of query result with " + - cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)" - + " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()); - - System.out.println("Item Ids " + cosmosItemPropertiesFeedResponse - .getResults() - .stream() - .map(Family::getId) - .collect(Collectors.toList())); - }); - // - } - - private void shutdown() { - try { - //Clean shutdown - System.out.println("Deleting Cosmos DB resources"); - System.out.println("-Deleting container..."); - if (container != null) - container.delete(); - System.out.println("-Deleting database..."); - if (database != null) - database.delete(); - System.out.println("-Closing the client..."); - } catch (Exception err) { - System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); - err.printStackTrace(); - } - client.close(); - System.out.println("Done."); - } -} diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java deleted file mode 100644 index 2ac24fb..0000000 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - - - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.storedprocedure.async; - -import com.azure.cosmos.*; -import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; -import com.azure.cosmos.examples.common.AccountSettings; -import com.azure.cosmos.examples.common.CustomPOJO; -import com.google.common.collect.Lists; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.util.UUID; -import java.util.concurrent.CountDownLatch; - -public class SampleStoredProcedureAsync { - - private CosmosAsyncClient client; - - private final String databaseName = "SprocTestDB"; - private final String containerName = "SprocTestContainer"; - - private CosmosAsyncDatabase database; - private CosmosAsyncContainer container; - - private String sprocId; - - protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); - - public void close() { - client.close(); - } - - /** - * Run a Hello CosmosDB console application. - * - * @param args command line args. - */ - //
- public static void main(String[] args) { - SampleStoredProcedureAsync p = new SampleStoredProcedureAsync(); - - try { - p.sprocDemo(); - System.out.println("Demo complete, please hold while resources are released"); - p.shutdown(); - System.out.println("Done.\n"); - } catch (Exception e) { - e.printStackTrace(); - System.out.println(String.format("Cosmos getStarted failed with %s", e)); - p.close(); - } finally { - } - } - - //
- - private void sprocDemo() throws Exception { - //Setup client, DB, and the container for which we will create stored procedures - //The container partition key will be id - setUp(); - - //Create stored procedure and list all stored procedures that have been created. - createStoredProcedure(); - readAllSprocs(); - - //Execute the stored procedure, which we expect will create an item with id test_doc - executeStoredProcedure(); - - //Perform a point-read to confirm that the item with id test_doc exists - System.out.println("Checking that a document was created by the stored procedure..."); - CosmosAsyncItemResponse test_resp = - container.readItem("test_doc",new PartitionKey("test_doc"),CustomPOJO.class).block(); - System.out.println(String.format( - "Status return value of point-read for document created by stored procedure (200 indicates success): %d",test_resp.getStatusCode())); - } - - public void setUp() throws Exception{ - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); - - ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); - // Setting the preferred location to Cosmos DB Account region - // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application - defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); - - // Create sync client - // - client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildAsyncClient(); - - System.out.println("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n"); - - client.createDatabaseIfNotExists(databaseName).flatMap(databaseResponse -> { - database = databaseResponse.getDatabase(); - return Mono.empty(); - }).block(); - - CosmosContainerProperties containerProperties = - new CosmosContainerProperties(containerName, "/id"); - database.createContainerIfNotExists(containerProperties, 400).flatMap(containerResponse -> { - container = containerResponse.getContainer(); - return Mono.empty(); - }).block(); - } - - public void shutdown() throws Exception { - //Safe clean & close - deleteStoredProcedure(); - } - - public void createStoredProcedure() throws Exception { - System.out.println("Creating stored procedure...\n"); - - sprocId = "createMyDocument"; - String sprocBody = "function createMyDocument() {\n" + - "var documentToCreate = {\"id\":\"test_doc\"}\n" + - "var context = getContext();\n" + - "var collection = context.getCollection();\n" + - "var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" + - " function (err, documentCreated) {\n" + - "if (err) throw new Error('Error' + err.message);\n" + - "context.getResponse().setBody(documentCreated.id)\n" + - "});\n" + - "if (!accepted) return;\n" + - "}"; - CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId,sprocBody); - container.getScripts() - .createStoredProcedure(storedProcedureDef, - new CosmosStoredProcedureRequestOptions()).block(); - } - - private void readAllSprocs() throws Exception { - - FeedOptions feedOptions = new FeedOptions(); - CosmosContinuablePagedFlux fluxResponse = - container.getScripts().readAllStoredProcedures(feedOptions); - - final CountDownLatch completionLatch = new CountDownLatch(1); - - - - fluxResponse.flatMap(storedProcedureProperties -> { - System.out.println(String.format("Stored Procedure: %s\n",storedProcedureProperties.getId())); - return Mono.empty(); - }).subscribe( - s -> {}, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.out.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} - ); - - completionLatch.await(); - } - - public void executeStoredProcedure() throws Exception { - System.out.println(String.format("Executing stored procedure %s...\n\n",sprocId)); - - CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions(); - options.setPartitionKey(new PartitionKey("test_doc")); - - container.getScripts() - .getStoredProcedure(sprocId) - .execute(null, options) - .flatMap(executeResponse -> { - System.out.println(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", - sprocId, - executeResponse.getResponseAsString(), - executeResponse.getStatusCode(), - executeResponse.getRequestCharge())); - return Mono.empty(); - }).block(); - } - - public void deleteStoredProcedure() throws Exception { - System.out.println("-Deleting stored procedure...\n"); - container.getScripts() - .getStoredProcedure(sprocId) - .delete().block(); - System.out.println("-Deleting database...\n"); - database.delete().block(); - System.out.println("-Closing client instance...\n"); - client.close(); - } -} diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java deleted file mode 100644 index fe96c54..0000000 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.cosmos.examples.storedprocedure.sync; - -import com.azure.cosmos.*; -import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; -import com.azure.cosmos.examples.common.AccountSettings; -import com.azure.cosmos.examples.common.CustomPOJO; -import com.azure.cosmos.implementation.Utils; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.Lists; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.UUID; -import java.util.Iterator; - -public class SampleStoredProcedure { - - private CosmosClient client; - - private final String databaseName = "SprocTestDB"; - private final String containerName = "SprocTestContainer"; - - private CosmosDatabase database; - private CosmosContainer container; - - private String sprocId; - - protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); - - public void close() { - client.close(); - } - - /** - * Run a Hello CosmosDB console application. - * - * @param args command line args. - */ - //
- public static void main(String[] args) { - SampleStoredProcedure p = new SampleStoredProcedure(); - - try { - p.sprocDemo(); - System.out.println("Demo complete, please hold while resources are released"); - p.shutdown(); - System.out.println("Done.\n"); - } catch (Exception e) { - e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); - p.close(); - } finally { - } - } - - //
- - private void sprocDemo() throws Exception { - //Setup client, DB, and the container for which we will create stored procedures - //The container partition key will be id - setUp(); - - //Create stored procedure and list all stored procedures that have been created. - createStoredProcedure(); - readAllSprocs(); - - //Execute the stored procedure, which we expect will create an item with id test_doc - executeStoredProcedure(); - - //Perform a point-read to confirm that the item with id test_doc exists - System.out.println("Checking that a document was created by the stored procedure..."); - CosmosItemResponse test_resp = container.readItem("test_doc",new PartitionKey("test_doc"),CustomPOJO.class); - System.out.println(String.format( - "Result of point-read for document created by stored procedure (200 indicates success): %d",test_resp.getStatusCode())); - } - - public void setUp() throws Exception{ - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); - - ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); - // Setting the preferred location to Cosmos DB Account region - // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application - defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); - - // Create sync client - // - client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildClient(); - - System.out.println("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n"); - - database = client.createDatabaseIfNotExists(databaseName).getDatabase(); - - CosmosContainerProperties containerProperties = - new CosmosContainerProperties(containerName, "/id"); - container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); - } - - public void shutdown() throws Exception { - //Safe clean & close - deleteStoredProcedure(); - } - - public void createStoredProcedure() throws Exception { - System.out.println("Creating stored procedure..."); - - sprocId = "createMyDocument"; - String sprocBody = "function createMyDocument() {\n" + - "var documentToCreate = {\"id\":\"test_doc\"}\n" + - "var context = getContext();\n" + - "var collection = context.getCollection();\n" + - "var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" + - " function (err, documentCreated) {\n" + - "if (err) throw new Error('Error' + err.message);\n" + - "context.getResponse().setBody(documentCreated.id)\n" + - "});\n" + - "if (!accepted) return;\n" + - "}"; - CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId,sprocBody); - container.getScripts() - .createStoredProcedure(storedProcedureDef, - new CosmosStoredProcedureRequestOptions()); - } - - private void readAllSprocs() throws Exception { - System.out.println("Listing all stored procedures associated with container " + containerName + "\n"); - - FeedOptions feedOptions = new FeedOptions(); - CosmosContinuablePagedIterable feedResponseIterable = - container.getScripts().readAllStoredProcedures(feedOptions); - - Iterator feedResponseIterator = feedResponseIterable.iterator(); - - while(feedResponseIterator.hasNext()) { - CosmosStoredProcedureProperties storedProcedureProperties = feedResponseIterator.next(); - System.out.println(String.format("Stored Procedure: %s",storedProcedureProperties)); - } - } - - public void executeStoredProcedure() throws Exception { - System.out.println(String.format("Executing stored procedure %s...\n\n",sprocId)); - - CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions(); - options.setPartitionKey(new PartitionKey("test_doc")); - CosmosStoredProcedureResponse executeResponse = container.getScripts() - .getStoredProcedure(sprocId) - .execute(null, options); - - System.out.println(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", - sprocId, - executeResponse.responseAsString(), - executeResponse.getStatusCode(), - executeResponse.getRequestCharge())); - } - - public void deleteStoredProcedure() throws Exception { - System.out.println("-Deleting stored procedure...\n"); - container.getScripts() - .getStoredProcedure(sprocId) - .delete(); - System.out.println("-Deleting database...\n"); - database.delete(); - System.out.println("-Closing client instance...\n"); - client.close(); - System.out.println("Done."); - } -} diff --git a/src/main/resources/log4j2.properties b/src/main/resources/log4j2.properties deleted file mode 100644 index 43f940f..0000000 --- a/src/main/resources/log4j2.properties +++ /dev/null @@ -1,21 +0,0 @@ -# this is the log4j configuration for tests - -# Set root logger level to WARN and its appender to STDOUT. -rootLogger.level = INFO -rootLogger.appenderRef.stdout.ref = STDOUT - -logger.netty.name = io.netty -logger.netty.level = INFO - -logger.reactor.name = io.reactivex -logger.reactor.level = INFO - -logger.cosmos.name = com.azure.cosmos -logger.cosmos.level = INFO - -# STDOUT is a ConsoleAppender and uses PatternLayout. -appender.console.name = STDOUT -appender.console.type = Console -appender.console.layout.type = PatternLayout -appender.console.layout.pattern = %m%n - diff --git a/src/main/resources/multi-master-sample-config.properties b/src/main/resources/multi-master-sample-config.properties deleted file mode 100644 index 42c2030..0000000 --- a/src/main/resources/multi-master-sample-config.properties +++ /dev/null @@ -1,8 +0,0 @@ -endpoint= -key= -regions=North Central US;North Europe;Southeast Asia -databaseName=multiMasterDemoDB -manualCollectionName=myManualCollection -lwwCollectionName=myLwwCollection -udpCollectionName=myUdpCollection -basicCollectionName=myBasicCollection \ No newline at end of file diff --git a/src/main/resources/resolver-storedproc.txt b/src/main/resources/resolver-storedproc.txt deleted file mode 100644 index e856721..0000000 --- a/src/main/resources/resolver-storedproc.txt +++ /dev/null @@ -1,45 +0,0 @@ -function resolver(incomingRecord, existingRecord, isTombstone, conflictingRecords) { - var collection = getContext().getCollection(); - if (!incomingRecord) { - if (existingRecord) { - collection.deleteDocument(existingRecord._self, {}, function(err, responseOptions) { - if (err) throw err; - }); - } - } else if (isTombstone) { - // delete always wins. - } else { - var documentToUse = incomingRecord; - if (existingRecord) { - if (documentToUse.regionId < existingRecord.regionId) { - documentToUse = existingRecord; - } - } - var i; - for (i = 0; i < conflictingRecords.length; i++) { - if (documentToUse.regionId < conflictingRecords[i].regionId) { - documentToUse = conflictingRecords[i]; - } - } - tryDelete(conflictingRecords, incomingRecord, existingRecord, documentToUse); - } - function tryDelete(documents, incoming, existing, documentToInsert) { - if (documents.length > 0) { - collection.deleteDocument(documents[0]._self, {}, function(err, responseOptions) { - if (err) throw err; - documents.shift(); - tryDelete(documents, incoming, existing, documentToInsert); - }); - } else if (existing) { - collection.replaceDocument(existing._self, documentToInsert, - function(err, documentCreated) { - if (err) throw err; - }); - } else { - collection.createDocument(collection.getSelfLink(), documentToInsert, - function(err, documentCreated) { - if (err) throw err; - }); - } - } -} \ No newline at end of file From f763fec948d2c7c220ceada87a7ffd9acce7b025 Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Mon, 9 Mar 2020 17:47:14 -0700 Subject: [PATCH 02/11] Added .gitignore --- .gitignore | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..00a9c64 --- /dev/null +++ b/.gitignore @@ -0,0 +1,51 @@ +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# idea files +/.idea/ + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Eclipse project file +*.project + +# Maven autogenerated classpath +*.classpath + +#VSCode Directories +/*.settings/ +/*.vscode/ +/target/ + +*.iml From e5a4af42f003dfb88df2092f15ffb263be5844e9 Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Mon, 9 Mar 2020 17:47:59 -0700 Subject: [PATCH 03/11] Java SDK v4 sample code --- CODE_OF_CONDUCT.md | 9 + LICENSE | 21 + README.md | 101 +++++ SECURITY.md | 41 ++ pom.xml | 83 ++++ .../changefeed/SampleChangeFeedProcessor.java | 270 +++++++++++++ .../changefeed/SampleConfigurations.java | 36 ++ .../examples/common/AccountSettings.java | 40 ++ .../azure/cosmos/examples/common/Address.java | 35 ++ .../azure/cosmos/examples/common/Child.java | 53 +++ .../cosmos/examples/common/CustomPOJO.java | 21 + .../cosmos/examples/common/Families.java | 117 ++++++ .../azure/cosmos/examples/common/Family.java | 74 ++++ .../azure/cosmos/examples/common/Parent.java | 33 ++ .../com/azure/cosmos/examples/common/Pet.java | 16 + .../async/SampleCRUDQuickstartAsync.java | 342 ++++++++++++++++ .../sync/SampleCRUDQuickstart.java | 251 ++++++++++++ .../async/SampleIndexManagementAsync.java | 368 ++++++++++++++++++ .../sync/SampleIndexManagement.java | 273 +++++++++++++ .../async/SampleStoredProcedureAsync.java | 207 ++++++++++ .../sync/SampleStoredProcedure.java | 174 +++++++++ src/main/resources/log4j2.properties | 21 + .../multi-master-sample-config.properties | 8 + src/main/resources/resolver-storedproc.txt | 45 +++ 24 files changed, 2639 insertions(+) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 pom.xml create mode 100644 src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java create mode 100644 src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java create mode 100644 src/main/java/com/azure/cosmos/examples/common/AccountSettings.java create mode 100644 src/main/java/com/azure/cosmos/examples/common/Address.java create mode 100644 src/main/java/com/azure/cosmos/examples/common/Child.java create mode 100644 src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java create mode 100644 src/main/java/com/azure/cosmos/examples/common/Families.java create mode 100644 src/main/java/com/azure/cosmos/examples/common/Family.java create mode 100644 src/main/java/com/azure/cosmos/examples/common/Parent.java create mode 100644 src/main/java/com/azure/cosmos/examples/common/Pet.java create mode 100644 src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java create mode 100644 src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java create mode 100644 src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java create mode 100644 src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java create mode 100644 src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java create mode 100644 src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java create mode 100644 src/main/resources/log4j2.properties create mode 100644 src/main/resources/multi-master-sample-config.properties create mode 100644 src/main/resources/resolver-storedproc.txt diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..f9ba8cf --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,9 @@ +# Microsoft Open Source Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). + +Resources: + +- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) +- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/README.md b/README.md new file mode 100644 index 0000000..219c639 --- /dev/null +++ b/README.md @@ -0,0 +1,101 @@ +--- +page_type: sample +languages: +- java +products: +- java sdk +description: "Sample code repo for Azure Cosmos DB Java SDK for SQL API" +urlFragment: "" +--- + +# Azure Cosmos DB Java SQL API Samples + + + +Sample code repo for Azure Cosmos DB Java SDK for SQL API. By cloning and running these samples, and then studying their implementations, you will have an example for sending various requests to Azure Cosmos DB from Java SDK via the SQL API. + +## Contents + +| File/folder | Description | +|-------------------|--------------------------------------------| +| `src` | Java sample source code. Many samples have 'sync' and 'async' variants | +| `.gitignore` | Define what to ignore at commit time. | +| `CHANGELOG.md` | List of changes to the sample. | +| `CONTRIBUTING.md` | Guidelines for contributing to the sample. | +| `README.md` | This README file. | +| `LICENSE` | The license for the sample. | +| `pom.xml` | Maven Project Object Model File + +## Prerequisites + +* A Java IDE such as IntelliJ IDEA or VSCode +* Maven +* Java SE JRE 8 +* Setting up an Azure Cosmos DB account through the Azure Portal. The **Create a database account** section of [this guide](https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-java) walks you through account creation. +* The hostname and master key for your Azure Cosmos DB account + +## Setup + +Clone the sample to your PC. Using your Java IDE, open pom.xml as a Maven project. + +## Running the sample + +*If you are using Intellij IDEA as your Java IDE:* Once you have opened the project, go to the **Run/Debug Configurations** drop-down and choose **Edit Configurations**. +In the **Edit Configurations** dialog, click the **+** (**Add New Configuration**) button, select **Application** as the configuration type, + and give the new configuration a name. Once you are looking at the settings for your new Configuration, find **Environment variables** and paste + +``` +ACCOUNT_HOST=your account hostname;ACCOUNT_KEY=your account master key +``` + +which gives the sample read/write access to your account. + +To choose which sample will run, populate the **Main class** field of the Configuration with + +``` +com.azure.cosmos.examples.changefeed.sample +``` + +where *sample* can be +* SampleCRUDQuickstart +* SampleCRUDQuickstartAsync +* SampleIndexManagement +* SampleIndexManagementAsync +* SampleStoredProcedure +* SampleStoredProcedureAsync +* SampleChangeFeedProcessor + +*Build and execute from command line without an IDE:* From top-level directory of repo: +``` +mvn clean package +mvn exec:java -Dexec.mainClass="com.azure.cosmos.examples.changefeed.sample" -DACCOUNT_HOST=your account hostname -DACCOUNT_KEY=your account master key +``` + +where *sample*, *your account hostname*, and *your account master key* are to be filled in as above. This will rebuild and run the selected sample. + +## Key concepts + +These samples cover a range of Azure Cosmos DB usage topics from more to less basic: +* Basic management of databases, containers and items +* Indexing, stored procedures +* Change Feed + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..e0dfff5 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)) of a security vulnerability, please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..57eb621 --- /dev/null +++ b/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + + com.azure + azure-cosmos-java-sql-api-samples + 1.0-SNAPSHOT + Get Started With Sync / Async Java SDK for SQL API of Azure Cosmos DB Database Service + + UTF-8 + + + + azure-sdk-for-java + https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 + + + + + azure-sdk-for-java + https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 + + true + + + true + + + + + + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + sync + + com.azure.cosmos.sample.sync.SyncMain + + + + async + + com.azure.cosmos.sample.async.AsyncMain + + + + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.8 + + + + org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 + + + + + + + + + com.azure + azure-cosmos + 4.0.0-preview.2 + + + \ No newline at end of file diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java new file mode 100644 index 0000000..c83cb82 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java @@ -0,0 +1,270 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.cosmos.examples.changefeed; + +import com.azure.cosmos.ChangeFeedProcessor; +import com.azure.cosmos.ConnectionPolicy; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosAsyncContainer; +import com.azure.cosmos.CosmosAsyncContainerResponse; +import com.azure.cosmos.CosmosAsyncDatabase; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosClientException; +import com.azure.cosmos.CosmosContainerProperties; +import com.azure.cosmos.CosmosContainerRequestOptions; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.examples.common.CustomPOJO; +import com.azure.cosmos.implementation.Utils; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.RandomStringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.scheduler.Schedulers; + +import java.time.Duration; +import java.util.List; + +/** + * Sample for Change Feed Processor. + * + */ +public class SampleChangeFeedProcessor { + + public static int WAIT_FOR_WORK = 60000; + public static final String DATABASE_NAME = "db_" + RandomStringUtils.randomAlphabetic(7); + public static final String COLLECTION_NAME = "coll_" + RandomStringUtils.randomAlphabetic(7); + private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper(); + protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); + + + private static ChangeFeedProcessor changeFeedProcessorInstance; + private static boolean isWorkCompleted = false; + + public static void main (String[]args) { + logger.info("BEGIN Sample"); + + try { + //This sample models an application where documents are being inserted into one container (the "feed container"), + //and meanwhile another worker thread or worker application is pulling inserted documents from the feed container's Change Feed + //and operating on them in some way. For one or more workers to process the Change Feed of a container, the workers must first contact the server + //and "lease" access to monitor one or more partitions of the feed container. The Change Feed Processor Library + //handles leasing automatically for you, however you must create a separate "lease container" where the Change Feed + //Processor Library can store and track leases container partitions. + + //Summary of the next four commands: + //-Create an asynchronous Azure Cosmos DB client and database so that we can issue async requests to the DB + //-Create a "feed container" and a "lease container" in the DB + System.out.println("-->CREATE DocumentClient"); + CosmosAsyncClient client = getCosmosClient(); + + System.out.println("-->CREATE sample's database: " + DATABASE_NAME); + CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME); + + System.out.println("-->CREATE container for documents: " + COLLECTION_NAME); + CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME); + + System.out.println("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); + CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); + + //Model of a worker thread or application which leases access to monitor one or more feed container + //partitions via the Change Feed. In a real-world application you might deploy this code in an Azure function. + //The next line causes the worker to create and start an instance of the Change Feed Processor. See the implementation of getChangeFeedProcessor() for guidance + //on creating a handler for Change Feed events. In this stream, we also trigger the insertion of 10 documents on a separate + //thread. + System.out.println("-->START Change Feed Processor on worker (handles changes asynchronously)"); + changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); + changeFeedProcessorInstance.start() + .subscribeOn(Schedulers.elastic()) + .doOnSuccess(aVoid -> { + //pass + }) + .subscribe(); + + //These two lines model an application which is inserting ten documents into the feed container + System.out.println("-->START application that inserts documents into feed container"); + createNewDocumentsCustomPOJO(feedContainer, 10, Duration.ofSeconds(3)); + isWorkCompleted = true; + + //This loop models the Worker main loop, which spins while its Change Feed Processor instance asynchronously + //handles incoming Change Feed events from the feed container. Of course in this sample, polling + //isWorkCompleted is unnecessary because items are being added to the feed container on the same thread, and you + //can see just above isWorkCompleted is set to true. + //But conceptually the worker is part of a different thread or application than the one which is inserting + //into the feed container; so this code illustrates the worker waiting and listening for changes to the feed container + long remainingWork = WAIT_FOR_WORK; + while (!isWorkCompleted && remainingWork > 0) { + Thread.sleep(100); + remainingWork -= 100; + } + + //When all documents have been processed, clean up + if (isWorkCompleted) { + if (changeFeedProcessorInstance != null) { + changeFeedProcessorInstance.stop().subscribe(); + } + } else { + throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); + } + + System.out.println("-->DELETE sample's database: " + DATABASE_NAME); + deleteDatabase(cosmosDatabase); + + Thread.sleep(500); + + } catch (Exception e) { + e.printStackTrace(); + } + + System.out.println("END Sample"); + } + + public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosAsyncContainer feedContainer, CosmosAsyncContainer leaseContainer) { + return ChangeFeedProcessor.changeFeedProcessorBuilder() + .setHostName(hostName) + .setFeedContainer(feedContainer) + .setLeaseContainer(leaseContainer) + .setHandleChanges((List docs) -> { + System.out.println("--->setHandleChanges() START"); + + for (JsonNode document : docs) { + try { + //Change Feed hands the document to you in the form of a JsonNode + //As a developer you have two options for handling the JsonNode document provided to you by Change Feed + //One option is to operate on the document in the form of a JsonNode, as shown below. This is great + //especially if you do not have a single uniform data model for all documents. + System.out.println("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() + .writeValueAsString(document)); + + //You can also transform the JsonNode to a POJO having the same structure as the JsonNode, + //as shown below. Then you can operate on the POJO. + CustomPOJO pojo_doc = OBJECT_MAPPER.treeToValue(document, CustomPOJO.class); + System.out.println("----=>id: " + pojo_doc.getId()); + + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } + System.out.println("--->handleChanges() END"); + + }) + .build(); + } + + public static CosmosAsyncClient getCosmosClient() { + + return new CosmosClientBuilder() + .setEndpoint(SampleConfigurations.HOST) + .setKey(SampleConfigurations.MASTER_KEY) + .setConnectionPolicy(ConnectionPolicy.getDefaultPolicy()) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildAsyncClient(); + } + + public static CosmosAsyncDatabase createNewDatabase(CosmosAsyncClient client, String databaseName) { + return client.createDatabaseIfNotExists(databaseName).block().getDatabase(); + } + + public static void deleteDatabase(CosmosAsyncDatabase cosmosDatabase) { + cosmosDatabase.delete().block(); + } + + public static CosmosAsyncContainer createNewCollection(CosmosAsyncClient client, String databaseName, String collectionName) { + CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); + CosmosAsyncContainer collectionLink = databaseLink.getContainer(collectionName); + CosmosAsyncContainerResponse containerResponse = null; + + try { + containerResponse = collectionLink.read().block(); + + if (containerResponse != null) { + throw new IllegalArgumentException(String.format("Collection %s already exists in database %s.", collectionName, databaseName)); + } + } catch (RuntimeException ex) { + if (ex instanceof CosmosClientException) { + CosmosClientException cosmosClientException = (CosmosClientException) ex; + + if (cosmosClientException.getStatusCode() != 404) { + throw ex; + } + } else { + throw ex; + } + } + + CosmosContainerProperties containerSettings = new CosmosContainerProperties(collectionName, "/id"); + CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); + containerResponse = databaseLink.createContainer(containerSettings, 10000, requestOptions).block(); + + if (containerResponse == null) { + throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName)); + } + + return containerResponse.getContainer(); + } + + public static CosmosAsyncContainer createNewLeaseCollection(CosmosAsyncClient client, String databaseName, String leaseCollectionName) { + CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); + CosmosAsyncContainer leaseCollectionLink = databaseLink.getContainer(leaseCollectionName); + CosmosAsyncContainerResponse leaseContainerResponse = null; + + try { + leaseContainerResponse = leaseCollectionLink.read().block(); + + if (leaseContainerResponse != null) { + leaseCollectionLink.delete().block(); + + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + } + } catch (RuntimeException ex) { + if (ex instanceof CosmosClientException) { + CosmosClientException cosmosClientException = (CosmosClientException) ex; + + if (cosmosClientException.getStatusCode() != 404) { + throw ex; + } + } else { + throw ex; + } + } + + CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id"); + CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); + + leaseContainerResponse = databaseLink.createContainer(containerSettings, 400,requestOptions).block(); + + if (leaseContainerResponse == null) { + throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); + } + + return leaseContainerResponse.getContainer(); + } + + public static void createNewDocumentsCustomPOJO(CosmosAsyncContainer containerClient, int count, Duration delay) { + String suffix = RandomStringUtils.randomAlphabetic(10); + for (int i = 0; i <= count; i++) { + CustomPOJO document = new CustomPOJO(); + document.setId(String.format("0%d-%s", i, suffix)); + + containerClient.createItem(document).subscribe(doc -> { + System.out.println("---->DOCUMENT WRITE: " + doc); + }); + + long remainingWork = delay.toMillis(); + try { + while (remainingWork > 0) { + Thread.sleep(100); + remainingWork -= 100; + } + } catch (InterruptedException iex) { + // exception caught + break; + } + } + } +} diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java new file mode 100644 index 0000000..86e75c7 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.cosmos.examples.changefeed; + +import com.google.common.base.Strings; +import org.apache.commons.lang3.StringUtils; + +/** + * Contains the configurations for tests. + *

+ * For running tests, you can pass a customized endpoint configuration in one of the following + * ways: + *

    + *
  • -DACCOUNT_KEY="[your-key]" -ACCOUNT_HOST="[your-endpoint]" as JVM + * command-line option.
  • + *
  • You can set ACCOUNT_KEY and ACCOUNT_HOST as environment variables.
  • + *
+ *

+ * If none of the above is set, emulator endpoint will be used. + */ +public final class SampleConfigurations { + // REPLACE MASTER_KEY and HOST with values from your Azure Cosmos DB account. + // The default values are credentials of the local emulator, which are not used in any production environment. + // + public static String MASTER_KEY = + System.getProperty("ACCOUNT_KEY", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("ACCOUNT_KEY")), + "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")); + + public static String HOST = + System.getProperty("ACCOUNT_HOST", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("ACCOUNT_HOST")), + "https://localhost:8081/")); +} diff --git a/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java b/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java new file mode 100644 index 0000000..12bb3ba --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.common; + +import org.apache.commons.lang3.StringUtils; + +/** + * Contains the account configurations for Sample. + * + * For running tests, you can pass a customized endpoint configuration in one of the following + * ways: + *

    + *
  • -DACCOUNT_KEY="[your-key]" -ACCOUNT_HOST="[your-endpoint]" as JVM + * command-line option.
  • + *
  • You can set ACCOUNT_KEY and ACCOUNT_HOST as environment variables.
  • + *
+ * + * If none of the above is set, emulator endpoint will be used. + * Emulator http cert is self signed. If you are using emulator, + * make sure emulator https certificate is imported + * to java trusted cert store: + * https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator-export-ssl-certificates + */ +public class AccountSettings { + // Replace MASTER_KEY and HOST with values from your Azure Cosmos DB account. + // The default values are credentials of the local emulator, which are not used in any production environment. + // + public static String MASTER_KEY = + System.getProperty("ACCOUNT_KEY", + StringUtils.defaultString(StringUtils.trimToNull( + System.getenv().get("ACCOUNT_KEY")), + "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")); + + public static String HOST = + System.getProperty("ACCOUNT_HOST", + StringUtils.defaultString(StringUtils.trimToNull( + System.getenv().get("ACCOUNT_HOST")), + "https://localhost:443/")); +} diff --git a/src/main/java/com/azure/cosmos/examples/common/Address.java b/src/main/java/com/azure/cosmos/examples/common/Address.java new file mode 100644 index 0000000..ec7d5b3 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/common/Address.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.common; + +public class Address { + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCounty() { + return county; + } + + public void setCounty(String county) { + this.county = county; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + private String state; + private String county; + private String city; +} + diff --git a/src/main/java/com/azure/cosmos/examples/common/Child.java b/src/main/java/com/azure/cosmos/examples/common/Child.java new file mode 100644 index 0000000..98cdd5c --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/common/Child.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.common; + +public class Child { + public String getFamilyName() { + return familyName; + } + + public void setFamilyName(String familyName) { + this.familyName = familyName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public int getGrade() { + return grade; + } + + public void setGrade(int grade) { + this.grade = grade; + } + + public Pet[] getPets() { + return pets; + } + + public void setPets(Pet[] pets) { + this.pets = pets; + } + + private String familyName; + private String firstName; + private String gender; + private int grade; + private Pet[] pets; +} + diff --git a/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java b/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java new file mode 100644 index 0000000..7704081 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java @@ -0,0 +1,21 @@ +package com.azure.cosmos.examples.common; + +public class CustomPOJO { + private String id; + + public CustomPOJO() { + + } + + public CustomPOJO(String id) { + this.id=id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } +} diff --git a/src/main/java/com/azure/cosmos/examples/common/Families.java b/src/main/java/com/azure/cosmos/examples/common/Families.java new file mode 100644 index 0000000..fd549ee --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/common/Families.java @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.common; + +public class Families { + + public static Family getAndersenFamilyItem() { + Family andersenFamily = new Family(); + andersenFamily.setId("Andersen-" + System.currentTimeMillis()); + andersenFamily.setLastName("Andersen"); + + Parent parent1 = new Parent(); + parent1.setFirstName("Thomas"); + + Parent parent2 = new Parent(); + parent2.setFirstName("Mary Kay"); + + andersenFamily.setParents(new Parent[] { parent1, parent2 }); + + Child child1 = new Child(); + child1.setFirstName("Henriette Thaulow"); + child1.setGender("female"); + child1.setGrade(5); + + Pet pet1 = new Pet(); + pet1.setGivenName("Fluffy"); + + child1.setPets(new Pet[] { pet1 }); + + andersenFamily.setDistrict("WA5"); + Address address = new Address(); + address.setCity("Seattle"); + address.setCounty("King"); + address.setState("WA"); + + andersenFamily.setAddress(address); + andersenFamily.setRegistered(true); + + return andersenFamily; + } + + public static Family getWakefieldFamilyItem() { + Family wakefieldFamily = new Family(); + wakefieldFamily.setId("Wakefield-" + System.currentTimeMillis()); + wakefieldFamily.setLastName("Wakefield"); + + Parent parent1 = new Parent(); + parent1.setFamilyName("Wakefield"); + parent1.setFirstName("Robin"); + + Parent parent2 = new Parent(); + parent2.setFamilyName("Miller"); + parent2.setFirstName("Ben"); + + wakefieldFamily.setParents(new Parent[] { parent1, parent2 }); + + Child child1 = new Child(); + child1.setFirstName("Jesse"); + child1.setFamilyName("Merriam"); + child1.setGrade(8); + + Pet pet1 = new Pet(); + pet1.setGivenName("Goofy"); + + Pet pet2 = new Pet(); + pet2.setGivenName("Shadow"); + + child1.setPets(new Pet[] { pet1, pet2 }); + + Child child2 = new Child(); + child2.setFirstName("Lisa"); + child2.setFamilyName("Miller"); + child2.setGrade(1); + child2.setGender("female"); + + wakefieldFamily.setChildren(new Child[] { child1, child2 }); + + Address address = new Address(); + address.setCity("NY"); + address.setCounty("Manhattan"); + address.setState("NY"); + + wakefieldFamily.setAddress(address); + wakefieldFamily.setDistrict("NY23"); + wakefieldFamily.setRegistered(true); + return wakefieldFamily; + } + + public static Family getJohnsonFamilyItem() { + Family andersenFamily = new Family(); + andersenFamily.setId("Johnson-" + System.currentTimeMillis()); + andersenFamily.setLastName("Johnson"); + + Parent parent1 = new Parent(); + parent1.setFirstName("John"); + + Parent parent2 = new Parent(); + parent2.setFirstName("Lili"); + + return andersenFamily; + } + + public static Family getSmithFamilyItem() { + Family andersenFamily = new Family(); + andersenFamily.setId("Smith-" + System.currentTimeMillis()); + andersenFamily.setLastName("Smith"); + + Parent parent1 = new Parent(); + parent1.setFirstName("John"); + + Parent parent2 = new Parent(); + parent2.setFirstName("Cynthia"); + + return andersenFamily; + } +} diff --git a/src/main/java/com/azure/cosmos/examples/common/Family.java b/src/main/java/com/azure/cosmos/examples/common/Family.java new file mode 100644 index 0000000..4e337b3 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/common/Family.java @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.common; + +public class Family { + public Family() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public Parent[] getParents() { + return parents; + } + + public void setParents(Parent[] parents) { + this.parents = parents; + } + + public Child[] getChildren() { + return children; + } + + public void setChildren(Child[] children) { + this.children = children; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public boolean isRegistered() { + return isRegistered; + } + + public void setRegistered(boolean isRegistered) { + this.isRegistered = isRegistered; + } + + private String id; + private String lastName; + private String district; + private Parent[] parents; + private Child[] children; + private Address address; + private boolean isRegistered; +} + diff --git a/src/main/java/com/azure/cosmos/examples/common/Parent.java b/src/main/java/com/azure/cosmos/examples/common/Parent.java new file mode 100644 index 0000000..d7753a8 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/common/Parent.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.common; + +public class Parent { + + public Parent() { + } + + public Parent(String firstName) { + this.firstName = firstName; + } + + public String getFamilyName() { + return familyName; + } + + public void setFamilyName(String familyName) { + this.familyName = familyName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + private String familyName; + private String firstName; +} diff --git a/src/main/java/com/azure/cosmos/examples/common/Pet.java b/src/main/java/com/azure/cosmos/examples/common/Pet.java new file mode 100644 index 0000000..062ce93 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/common/Pet.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.common; + +public class Pet { + public String getGivenName() { + return givenName; + } + + public void setGivenName(String givenName) { + this.givenName = givenName; + } + + private String givenName; +} diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java new file mode 100644 index 0000000..3e5b581 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java @@ -0,0 +1,342 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.crudquickstart.async; + + +import com.azure.cosmos.*; +import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; +import com.azure.cosmos.examples.common.AccountSettings; +import com.azure.cosmos.examples.common.Families; +import com.azure.cosmos.examples.common.Family; +import com.google.common.collect.Lists; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.util.concurrent.CountDownLatch; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SampleCRUDQuickstartAsync { + + private CosmosAsyncClient client; + + private final String databaseName = "AzureSampleFamilyDB"; + private final String containerName = "FamilyContainer"; + + private CosmosAsyncDatabase database; + private CosmosAsyncContainer container; + + protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); + + public void close() { + client.close(); + } + + /** + * Run a Hello CosmosDB console application. + * + * @param args command line args. + */ + //
+ public static void main(String[] args) { + SampleCRUDQuickstartAsync p = new SampleCRUDQuickstartAsync(); + + try { + System.out.println("Starting ASYNC main"); + p.getStartedDemo(); + System.out.println("Demo complete, please hold while resources are released"); + } catch (Exception e) { + e.printStackTrace(); + System.err.println(String.format("Cosmos getStarted failed with %s", e)); + } finally { + System.out.println("Closing the client"); + p.shutdown(); + } + } + + //
+ + private void getStartedDemo() throws Exception { + //This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations + //with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will + //1. Create asynchronous client, database and container instances + //2. Create several items + //3. Upsert one of the items + //4. Perform a query over the items + //5. Delete an item + //6. Delete the Cosmos DB database and container resources and close the client. + + System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + + ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); + // Setting the preferred location to Cosmos DB Account region + // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application + defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); + + // Create async client + // + client = new CosmosClientBuilder() + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildAsyncClient(); + + // + + createDatabaseIfNotExists(); + createContainerIfNotExists(); + + Family andersenFamilyItem=Families.getAndersenFamilyItem(); + Family wakefieldFamilyItem=Families.getWakefieldFamilyItem(); + Family johnsonFamilyItem=Families.getJohnsonFamilyItem(); + Family smithFamilyItem=Families.getSmithFamilyItem(); + + // Setup family items to create + Flux familiesToCreate = Flux.just(andersenFamilyItem, + wakefieldFamilyItem, + johnsonFamilyItem, + smithFamilyItem); + + // Creates several items in the container + createFamilies(familiesToCreate); + + // Upsert one of the items in the container + upsertFamily(wakefieldFamilyItem); + + familiesToCreate = Flux.just(andersenFamilyItem, + wakefieldFamilyItem, + johnsonFamilyItem, + smithFamilyItem); + + System.out.println("Reading items."); + readItems(familiesToCreate); + + System.out.println("Querying items."); + queryItems(); + + System.out.println("Deleting an item."); + deleteItem(andersenFamilyItem); + } + + private void createDatabaseIfNotExists() throws Exception { + System.out.println("Create database " + databaseName + " if not exists."); + + // Create database if not exists + // + Mono databaseIfNotExists = client.createDatabaseIfNotExists(databaseName); + databaseIfNotExists.flatMap(databaseResponse -> { + database = databaseResponse.getDatabase(); + System.out.println("Checking database " + database.getId() + " completed!\n"); + return Mono.empty(); + }).block(); + // + } + + private void createContainerIfNotExists() throws Exception { + System.out.println("Create container " + containerName + " if not exists."); + + // Create container if not exists + // + + CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/lastName"); + Mono containerIfNotExists = database.createContainerIfNotExists(containerProperties, 400); + + // Create container with 400 RU/s + containerIfNotExists.flatMap(containerResponse -> { + container = containerResponse.getContainer(); + System.out.println("Checking container " + container.getId() + " completed!\n"); + return Mono.empty(); + }).block(); + + // + } + + private void createFamilies(Flux families) throws Exception { + + // + + final CountDownLatch completionLatch = new CountDownLatch(1); + + // Combine multiple item inserts, associated success println's, and a final aggregate stats println into one Reactive stream. + families.flatMap(family -> { + return container.createItem(family); + }) //Flux of item request responses + .flatMap(itemResponse -> { + System.out.println(String.format("Created item with request charge of %.2f within" + + " duration %s", + itemResponse.getRequestCharge(), itemResponse.getRequestLatency())); + System.out.println(String.format("Item ID: %s\n", itemResponse.getResource().getId())); + return Mono.just(itemResponse.getRequestCharge()); + }) //Flux of request charges + .reduce(0.0, + (charge_n,charge_nplus1) -> charge_n + charge_nplus1 + ) //Mono of total charge - there will be only one item in this stream + .subscribe(charge -> { + System.out.println(String.format("Created items with total request charge of %.2f\n", + charge)); + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException)err; + cerr.printStackTrace(); + System.err.println(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> {completionLatch.countDown();} + ); //Preserve the total charge and print aggregate charge/item count stats. + + try { + completionLatch.await(); + } catch (InterruptedException err) { + throw new AssertionError("Unexpected Interruption",err); + } + + // + } + + private void upsertFamily(Family family_to_upsert) { + //Modify a field of the family object + System.out.println(String.format("Upserting the item with id %s after modifying the isRegistered field...",family_to_upsert.getId())); + family_to_upsert.setRegistered(!family_to_upsert.isRegistered()); + + //Upsert the modified item + Mono.just(family_to_upsert).flatMap(item -> { + CosmosAsyncItemResponse item_resp = container.upsertItem(family_to_upsert).block(); + + // Get upsert request charge and other properties like latency, and diagnostics strings, etc. + System.out.println(String.format("Upserted item with request charge of %.2f within duration %s", + item_resp.getRequestCharge(), item_resp.getRequestLatency())); + + return Mono.empty(); + }).subscribe(); + } + + private void readItems(Flux familiesToCreate) { + // Using partition key for point read scenarios. + // This will help fast look up of items because of partition key + // + + final CountDownLatch completionLatch = new CountDownLatch(1); + + familiesToCreate.flatMap(family -> { + Mono> asyncItemResponseMono = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); + return asyncItemResponseMono; + }) + .subscribe( + itemResponse -> { + double requestCharge = itemResponse.getRequestCharge(); + Duration requestLatency = itemResponse.getRequestLatency(); + System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", + itemResponse.getResource().getId(), requestCharge, requestLatency)); + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException)err; + cerr.printStackTrace(); + System.err.println(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> {completionLatch.countDown();} + ); + + try { + completionLatch.await(); + } catch (InterruptedException err) { + throw new AssertionError("Unexpected Interruption",err); + } + + // + } + + private void queryItems() { + // + // Set some common query options + + FeedOptions queryOptions = new FeedOptions(); + queryOptions.maxItemCount(10); + //queryOptions.setEnableCrossPartitionQuery(true); //No longer needed in SDK v4 + // Set populate query metrics to get metrics around query executions + queryOptions.populateQueryMetrics(true); + + CosmosContinuablePagedFlux pagedFluxResponse = container.queryItems( + "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); + + final CountDownLatch completionLatch = new CountDownLatch(1); + + pagedFluxResponse.byPage().subscribe( + fluxResponse -> { + System.out.println("Got a page of query result with " + + fluxResponse.getResults().size() + " items(s)" + + " and request charge of " + fluxResponse.getRequestCharge()); + + System.out.println("Item Ids " + fluxResponse + .getResults() + .stream() + .map(Family::getId) + .collect(Collectors.toList())); + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException)err; + cerr.printStackTrace(); + System.err.println(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> {completionLatch.countDown();} + ); + + try { + completionLatch.await(); + } catch (InterruptedException err) { + throw new AssertionError("Unexpected Interruption",err); + } + + // + } + + private void deleteItem(Family item) { + container.deleteItem(item.getId(),new PartitionKey(item.getLastName())).block(); + } + + private void shutdown() { + try { + //Clean shutdown + System.out.println("Deleting Cosmos DB resources"); + System.out.println("-Deleting container..."); + if (container != null) + container.delete().subscribe(); + System.out.println("-Deleting database..."); + if (database != null) + database.delete().subscribe(); + System.out.println("-Closing the client..."); + } catch (Exception err) { + System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); + err.printStackTrace(); + } + client.close(); + System.out.println("Done."); + } +} diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java new file mode 100644 index 0000000..293cd35 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.crudquickstart.sync; + +import com.azure.cosmos.ConnectionPolicy; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosClientException; +import com.azure.cosmos.CosmosContainer; +import com.azure.cosmos.CosmosContainerProperties; +import com.azure.cosmos.CosmosContinuablePagedIterable; +import com.azure.cosmos.CosmosDatabase; +import com.azure.cosmos.CosmosItemRequestOptions; +import com.azure.cosmos.CosmosItemResponse; +import com.azure.cosmos.FeedOptions; +import com.azure.cosmos.PartitionKey; +import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; +import com.azure.cosmos.examples.common.AccountSettings; +import com.azure.cosmos.examples.common.Families; +import com.azure.cosmos.examples.common.Family; +import com.google.common.collect.Lists; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SampleCRUDQuickstart { + + private CosmosClient client; + + private final String databaseName = "AzureSampleFamilyDB"; + private final String containerName = "FamilyContainer"; + + private CosmosDatabase database; + private CosmosContainer container; + + protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); + + public void close() { + client.close(); + } + + /** + * Run a Hello CosmosDB console application. + * + * @param args command line args. + */ + //
+ public static void main(String[] args) { + SampleCRUDQuickstart p = new SampleCRUDQuickstart(); + + try { + System.out.println("Starting SYNC main"); + p.getStartedDemo(); + System.out.println("Demo complete, please hold while resources are released"); + } catch (Exception e) { + e.printStackTrace(); + System.err.println(String.format("Cosmos getStarted failed with %s", e)); + } finally { + System.out.println("Closing the client"); + p.shutdown(); + } + } + + //
+ + private void getStartedDemo() throws Exception { + //This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations + //with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will + //1. Create synchronous client, database and container instances + //2. Create several items + //3. Upsert one of the items + //4. Perform a query over the items + //5. Delete an item + //6. Delete the Cosmos DB database and container resources and close the client. + + System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + + ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); + // Setting the preferred location to Cosmos DB Account region + // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application + defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); + + // Create sync client + // + client = new CosmosClientBuilder() + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildClient(); + + // + + createDatabaseIfNotExists(); + createContainerIfNotExists(); + + // Setup family items to create + ArrayList familiesToCreate = new ArrayList<>(); + familiesToCreate.add(Families.getAndersenFamilyItem()); + familiesToCreate.add(Families.getWakefieldFamilyItem()); + familiesToCreate.add(Families.getJohnsonFamilyItem()); + familiesToCreate.add(Families.getSmithFamilyItem()); + + // Creates several items in the container + // Also applies an upsert operation to one of the items (create if not present, otherwise replace) + createFamilies(familiesToCreate); + + System.out.println("Reading items."); + readItems(familiesToCreate); + + System.out.println("Querying items."); + queryItems(); + + System.out.println("Delete an item."); + deleteItem(familiesToCreate.get(0)); + } + + private void createDatabaseIfNotExists() throws Exception { + System.out.println("Create database " + databaseName + " if not exists."); + + // Create database if not exists + // + database = client.createDatabaseIfNotExists(databaseName).getDatabase(); + // + + System.out.println("Checking database " + database.getId() + " completed!\n"); + } + + private void createContainerIfNotExists() throws Exception { + System.out.println("Create container " + containerName + " if not exists."); + + // Create container if not exists + // + CosmosContainerProperties containerProperties = + new CosmosContainerProperties(containerName, "/lastName"); + + // Create container with 400 RU/s + container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); + // + + System.out.println("Checking container " + container.getId() + " completed!\n"); + } + + private void createFamilies(List families) throws Exception { + double totalRequestCharge = 0; + for (Family family : families) { + + // + // Create item using container that we created using sync client + + // Use lastName as partitionKey for cosmos item + // Using appropriate partition key improves the performance of database operations + CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); + CosmosItemResponse item = container.createItem(family, new PartitionKey(family.getLastName()), cosmosItemRequestOptions); + // + + // Get request charge and other properties like latency, and diagnostics strings, etc. + System.out.println(String.format("Created item with request charge of %.2f within duration %s", + item.getRequestCharge(), item.getRequestLatency())); + + totalRequestCharge += item.getRequestCharge(); + } + System.out.println(String.format("Created %d items with total request charge of %.2f", + families.size(), totalRequestCharge)); + + Family family_to_upsert = families.get(0); + System.out.println(String.format("Upserting the item with id %s after modifying the isRegistered field...",family_to_upsert.getId())); + family_to_upsert.setRegistered(!family_to_upsert.isRegistered()); + + CosmosItemResponse item = container.upsertItem(family_to_upsert); + + // Get upsert request charge and other properties like latency, and diagnostics strings, etc. + System.out.println(String.format("Upserted item with request charge of %.2f within duration %s", + item.getRequestCharge(), item.getRequestLatency())); + } + + private void readItems(ArrayList familiesToCreate) { + // Using partition key for point read scenarios. + // This will help fast look up of items because of partition key + familiesToCreate.forEach(family -> { + // + try { + CosmosItemResponse item = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); + double requestCharge = item.getRequestCharge(); + Duration requestLatency = item.getRequestLatency(); + System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", + item.getResource().getId(), requestCharge, requestLatency)); + } catch (CosmosClientException e) { + e.printStackTrace(); + System.out.println(String.format("Read Item failed with %s", e)); + } + // + }); + } + + private void queryItems() { + // + // Set some common query options + FeedOptions queryOptions = new FeedOptions(); + queryOptions.maxItemCount(10); + //queryOptions.setEnableCrossPartitionQuery(true); //No longer necessary in SDK v4 + // Set populate query metrics to get metrics around query executions + queryOptions.populateQueryMetrics(true); + + CosmosContinuablePagedIterable familiesPagedIterable = container.queryItems( + "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); + + familiesPagedIterable.iterableByPage().forEach(cosmosItemPropertiesFeedResponse -> { + System.out.println("Got a page of query result with " + + cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)" + + " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()); + + System.out.println("Item Ids " + cosmosItemPropertiesFeedResponse + .getResults() + .stream() + .map(Family::getId) + .collect(Collectors.toList())); + }); + // + } + + private void deleteItem(Family item) { + container.deleteItem(item.getId(),new PartitionKey(item.getLastName()),new CosmosItemRequestOptions()); + } + + private void shutdown() { + try { + //Clean shutdown + System.out.println("Deleting Cosmos DB resources"); + System.out.println("-Deleting container..."); + if (container != null) + container.delete(); + System.out.println("-Deleting database..."); + if (database != null) + database.delete(); + System.out.println("-Closing the client..."); + } catch (Exception err) { + System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); + err.printStackTrace(); + } + client.close(); + System.out.println("Done."); + } +} diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java new file mode 100644 index 0000000..b335434 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java @@ -0,0 +1,368 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.indexmanagement.async; + +import com.azure.cosmos.*; +import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; +import com.azure.cosmos.examples.common.AccountSettings; +import com.azure.cosmos.examples.common.Families; +import com.azure.cosmos.examples.common.Family; +import com.google.common.collect.Lists; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SampleIndexManagementAsync { + + private CosmosAsyncClient client; + + private final String databaseName = "AzureSampleFamilyDB"; + private final String containerName = "FamilyContainer"; + + private CosmosAsyncDatabase database; + private CosmosAsyncContainer container; + + protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); + + public void close() { + client.close(); + } + + /** + * Run a Hello CosmosDB console application. + * + * @param args command line args. + */ + //
+ public static void main(String[] args) { + SampleIndexManagementAsync p = new SampleIndexManagementAsync(); + + try { + System.out.println("Starting ASYNC main"); + p.indexManagementDemo(); + System.out.println("Demo complete, please hold while resources are released"); + } catch (Exception e) { + e.printStackTrace(); + System.err.println(String.format("Cosmos getStarted failed with %s", e)); + } finally { + System.out.println("Closing the client"); + p.shutdown(); + } + } + + //
+ + private void indexManagementDemo() throws Exception { + //This sample is similar to SampleCRUDQuickstartAsync, but modified to show indexing capabilities of Cosmos DB. + //Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of + //indexing capabilities. + + System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + + ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); + // Setting the preferred location to Cosmos DB Account region + // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application + defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); + + // Create async client + // + client = new CosmosClientBuilder() + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildAsyncClient(); + + // + + createDatabaseIfNotExists(); + + //Here is where index management is performed + createContainerIfNotExistsWithSpecifiedIndex(); + + Family andersenFamilyItem=Families.getAndersenFamilyItem(); + Family wakefieldFamilyItem=Families.getWakefieldFamilyItem(); + Family johnsonFamilyItem=Families.getJohnsonFamilyItem(); + Family smithFamilyItem=Families.getSmithFamilyItem(); + + // Setup family items to create + Flux familiesToCreate = Flux.just(andersenFamilyItem, + wakefieldFamilyItem, + johnsonFamilyItem, + smithFamilyItem); + + createFamilies(familiesToCreate); + + familiesToCreate = Flux.just(andersenFamilyItem, + wakefieldFamilyItem, + johnsonFamilyItem, + smithFamilyItem); + + System.out.println("Reading items."); + readItems(familiesToCreate); + + System.out.println("Querying items."); + queryItems(); + } + + private void createDatabaseIfNotExists() throws Exception { + System.out.println("Create database " + databaseName + " if not exists."); + + // Create database if not exists + // + Mono databaseIfNotExists = client.createDatabaseIfNotExists(databaseName); + databaseIfNotExists.flatMap(databaseResponse -> { + database = databaseResponse.getDatabase(); + System.out.println("Checking database " + database.getId() + " completed!\n"); + return Mono.empty(); + }).block(); + // + } + + private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception { + System.out.println("Create container " + containerName + " if not exists."); + + // Create container if not exists + // + + CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/lastName"); + + // + IndexingPolicy indexingPolicy = new IndexingPolicy(); + indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); //To turn indexing off set IndexingMode.NONE + + // Included paths + List includedPaths = new ArrayList<>(); + IncludedPath includedPath = new IncludedPath(); + includedPath.setPath("/*"); + includedPaths.add(includedPath); + indexingPolicy.setIncludedPaths(includedPaths); + + // Excluded paths + List excludedPaths = new ArrayList<>(); + ExcludedPath excludedPath = new ExcludedPath(); + excludedPath.setPath("/name/*"); + excludedPaths.add(excludedPath); + indexingPolicy.setExcludedPaths(excludedPaths); + + // Spatial indices - if you need them, here is how to set them up: + /* + List spatialIndexes = new ArrayList(); + List collectionOfSpatialTypes = new ArrayList(); + + SpatialSpec spec = new SpatialSpec(); + spec.setPath("/locations/*"); + collectionOfSpatialTypes.add(SpatialType.Point); + spec.setSpatialTypes(collectionOfSpatialTypes); + spatialIndexes.add(spec); + + indexingPolicy.setSpatialIndexes(spatialIndexes); + */ + + // Composite indices - if you need them, here is how to set them up: + /* + List> compositeIndexes = new ArrayList<>(); + List compositePaths = new ArrayList<>(); + + CompositePath nameCompositePath = new CompositePath(); + nameCompositePath.setPath("/name"); + nameCompositePath.setOrder(CompositePathSortOrder.ASCENDING); + + CompositePath ageCompositePath = new CompositePath(); + ageCompositePath.setPath("/age"); + ageCompositePath.setOrder(CompositePathSortOrder.DESCENDING); + + compositePaths.add(ageCompositePath); + compositePaths.add(nameCompositePath); + + compositeIndexes.add(compositePaths); + indexingPolicy.setCompositeIndexes(compositeIndexes); + */ + + containerProperties.setIndexingPolicy(indexingPolicy); + + // + + Mono containerIfNotExists = database.createContainerIfNotExists(containerProperties, 400); + + // Create container with 400 RU/s + containerIfNotExists.flatMap(containerResponse -> { + container = containerResponse.getContainer(); + System.out.println("Checking container " + container.getId() + " completed!\n"); + return Mono.empty(); + }).block(); + + // + } + + private void createFamilies(Flux families) throws Exception { + + // + + final CountDownLatch completionLatch = new CountDownLatch(1); + + // Combine multiple item inserts, associated success println's, and a final aggregate stats println into one Reactive stream. + families.flatMap(family -> { + return container.createItem(family); + }) //Flux of item request responses + .flatMap(itemResponse -> { + System.out.println(String.format("Created item with request charge of %.2f within" + + " duration %s", + itemResponse.getRequestCharge(), itemResponse.getRequestLatency())); + System.out.println(String.format("Item ID: %s\n", itemResponse.getResource().getId())); + return Mono.just(itemResponse.getRequestCharge()); + }) //Flux of request charges + .reduce(0.0, + (charge_n,charge_nplus1) -> charge_n + charge_nplus1 + ) //Mono of total charge - there will be only one item in this stream + .subscribe(charge -> { + System.out.println(String.format("Created items with total request charge of %.2f\n", + charge)); + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException)err; + cerr.printStackTrace(); + System.out.println(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> {completionLatch.countDown();} + ); //Preserve the total charge and print aggregate charge/item count stats. + + try { + completionLatch.await(); + } catch (InterruptedException err) { + throw new AssertionError("Unexpected Interruption",err); + } + + // + } + + private void readItems(Flux familiesToCreate) { + // Using partition key for point read scenarios. + // This will help fast look up of items because of partition key + // + + final CountDownLatch completionLatch = new CountDownLatch(1); + + familiesToCreate.flatMap(family -> { + Mono> asyncItemResponseMono = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); + return asyncItemResponseMono; + }) + .subscribe( + itemResponse -> { + double requestCharge = itemResponse.getRequestCharge(); + Duration requestLatency = itemResponse.getRequestLatency(); + System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", + itemResponse.getResource().getId(), requestCharge, requestLatency)); + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException)err; + cerr.printStackTrace(); + System.out.println(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> {completionLatch.countDown();} + ); + + try { + completionLatch.await(); + } catch (InterruptedException err) { + throw new AssertionError("Unexpected Interruption",err); + } + + // + } + + private void queryItems() { + // + // Set some common query options + + FeedOptions queryOptions = new FeedOptions(); + queryOptions.maxItemCount(10); + // Set populate query metrics to get metrics around query executions + queryOptions.populateQueryMetrics(true); + + CosmosContinuablePagedFlux pagedFluxResponse = container.queryItems( + "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); + + final CountDownLatch completionLatch = new CountDownLatch(1); + + pagedFluxResponse.byPage().subscribe( + fluxResponse -> { + System.out.println("Got a page of query result with " + + fluxResponse.getResults().size() + " items(s)" + + " and request charge of " + fluxResponse.getRequestCharge()); + + System.out.println("Item Ids " + fluxResponse + .getResults() + .stream() + .map(Family::getId) + .collect(Collectors.toList())); + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException)err; + cerr.printStackTrace(); + System.err.println(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> {completionLatch.countDown();} + ); + + try { + completionLatch.await(); + } catch (InterruptedException err) { + throw new AssertionError("Unexpected Interruption",err); + } + + // + } + + private void shutdown() { + try { + //Clean shutdown + System.out.println("Deleting Cosmos DB resources"); + System.out.println("-Deleting container..."); + if (container != null) + container.delete().subscribe(); + System.out.println("-Deleting database..."); + if (database != null) + database.delete().subscribe(); + System.out.println("-Closing the client..."); + } catch (Exception err) { + System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); + err.printStackTrace(); + } + client.close(); + System.out.println("Done."); + } +} diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java new file mode 100644 index 0000000..fc07cab --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java @@ -0,0 +1,273 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.indexmanagement.sync; + +import com.azure.cosmos.*; +import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; +import com.azure.cosmos.examples.common.AccountSettings; +import com.azure.cosmos.examples.common.Families; +import com.azure.cosmos.examples.common.Family; +import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +public class SampleIndexManagement { + + private CosmosClient client; + + private final String databaseName = "AzureSampleFamilyDB"; + private final String containerName = "FamilyContainer"; + + private CosmosDatabase database; + private CosmosContainer container; + + protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); + + public void close() { + client.close(); + } + + /** + * Run a Hello CosmosDB console application. + * + * @param args command line args. + */ + //
+ public static void main(String[] args) { + + SampleIndexManagement p = new SampleIndexManagement(); + + try { + System.out.println("Starting SYNC main"); + p.indexManagementDemo(); + System.out.println("Demo complete, please hold while resources are released"); + } catch (Exception e) { + e.printStackTrace(); + System.err.println(String.format("Cosmos getStarted failed with %s", e)); + } finally { + System.out.println("Closing the client"); + p.shutdown(); + } + } + + //
+ + private void indexManagementDemo() throws Exception { + //This sample is similar to SampleCRUDQuickstart, but modified to show indexing capabilities of Cosmos DB. + //Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of + //indexing capabilities. + + System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + + ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); + // Setting the preferred location to Cosmos DB Account region + // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application + defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); + + // Create sync client + // + client = new CosmosClientBuilder() + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildClient(); + + // + + createDatabaseIfNotExists(); + + //Here is where index management is performed + createContainerIfNotExistsWithSpecifiedIndex(); + + // Setup family items to create + ArrayList familiesToCreate = new ArrayList<>(); + familiesToCreate.add(Families.getAndersenFamilyItem()); + familiesToCreate.add(Families.getWakefieldFamilyItem()); + familiesToCreate.add(Families.getJohnsonFamilyItem()); + familiesToCreate.add(Families.getSmithFamilyItem()); + + createFamilies(familiesToCreate); + + System.out.println("Reading items."); + readItems(familiesToCreate); + + System.out.println("Querying items."); + queryItems(); + } + + private void createDatabaseIfNotExists() throws Exception { + System.out.println("Create database " + databaseName + " if not exists."); + + // Create database if not exists + // + database = client.createDatabaseIfNotExists(databaseName).getDatabase(); + // + + System.out.println("Checking database " + database.getId() + " completed!\n"); + } + + private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception { + System.out.println("Create container " + containerName + " if not exists."); + + // Create container if not exists + CosmosContainerProperties containerProperties = + new CosmosContainerProperties(containerName, "/lastName"); + + // + IndexingPolicy indexingPolicy = new IndexingPolicy(); + indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); //To turn indexing off set IndexingMode.NONE + + // Included paths + List includedPaths = new ArrayList<>(); + IncludedPath includedPath = new IncludedPath(); + includedPath.setPath("/*"); + includedPaths.add(includedPath); + indexingPolicy.setIncludedPaths(includedPaths); + + // Excluded paths + List excludedPaths = new ArrayList<>(); + ExcludedPath excludedPath = new ExcludedPath(); + excludedPath.setPath("/name/*"); + excludedPaths.add(excludedPath); + indexingPolicy.setExcludedPaths(excludedPaths); + + // Spatial indices - if you need them, here is how to set them up: + /* + List spatialIndexes = new ArrayList(); + List collectionOfSpatialTypes = new ArrayList(); + + SpatialSpec spec = new SpatialSpec(); + spec.setPath("/locations/*"); + collectionOfSpatialTypes.add(SpatialType.Point); + spec.setSpatialTypes(collectionOfSpatialTypes); + spatialIndexes.add(spec); + + indexingPolicy.setSpatialIndexes(spatialIndexes); + */ + + // Composite indices - if you need them, here is how to set them up: + /* + List> compositeIndexes = new ArrayList<>(); + List compositePaths = new ArrayList<>(); + + CompositePath nameCompositePath = new CompositePath(); + nameCompositePath.setPath("/name"); + nameCompositePath.setOrder(CompositePathSortOrder.ASCENDING); + + CompositePath ageCompositePath = new CompositePath(); + ageCompositePath.setPath("/age"); + ageCompositePath.setOrder(CompositePathSortOrder.DESCENDING); + + compositePaths.add(ageCompositePath); + compositePaths.add(nameCompositePath); + + compositeIndexes.add(compositePaths); + indexingPolicy.setCompositeIndexes(compositeIndexes); + */ + + containerProperties.setIndexingPolicy(indexingPolicy); + + // + + // Create container with 400 RU/s + container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); + + System.out.println("Checking container " + container.getId() + " completed!\n"); + } + + private void createFamilies(List families) throws Exception { + double totalRequestCharge = 0; + for (Family family : families) { + + // + // Create item using container that we created using sync client + + // Use lastName as partitionKey for cosmos item + // Using appropriate partition key improves the performance of database operations + CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); + CosmosItemResponse item = container.createItem(family, new PartitionKey(family.getLastName()), cosmosItemRequestOptions); + // + + // Get request charge and other properties like latency, and diagnostics strings, etc. + System.out.println(String.format("Created item with request charge of %.2f within" + + " duration %s", + item.getRequestCharge(), item.getRequestLatency())); + totalRequestCharge += item.getRequestCharge(); + } + System.out.println(String.format("Created %d items with total request " + + "charge of %.2f", + families.size(), + totalRequestCharge)); + } + + private void readItems(ArrayList familiesToCreate) { + // Using partition key for point read scenarios. + // This will help fast look up of items because of partition key + familiesToCreate.forEach(family -> { + // + try { + CosmosItemResponse item = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); + double requestCharge = item.getRequestCharge(); + Duration requestLatency = item.getRequestLatency(); + System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", + item.getResource().getId(), requestCharge, requestLatency)); + } catch (CosmosClientException e) { + e.printStackTrace(); + System.err.println(String.format("Read Item failed with %s", e)); + } + // + }); + } + + private void queryItems() { + // + // Set some common query options + FeedOptions queryOptions = new FeedOptions(); + queryOptions.maxItemCount(10); + // Set populate query metrics to get metrics around query executions + queryOptions.populateQueryMetrics(true); + + CosmosContinuablePagedIterable familiesPagedIterable = container.queryItems( + "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); + + familiesPagedIterable.iterableByPage().forEach(cosmosItemPropertiesFeedResponse -> { + System.out.println("Got a page of query result with " + + cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)" + + " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()); + + System.out.println("Item Ids " + cosmosItemPropertiesFeedResponse + .getResults() + .stream() + .map(Family::getId) + .collect(Collectors.toList())); + }); + // + } + + private void shutdown() { + try { + //Clean shutdown + System.out.println("Deleting Cosmos DB resources"); + System.out.println("-Deleting container..."); + if (container != null) + container.delete(); + System.out.println("-Deleting database..."); + if (database != null) + database.delete(); + System.out.println("-Closing the client..."); + } catch (Exception err) { + System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); + err.printStackTrace(); + } + client.close(); + System.out.println("Done."); + } +} diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java new file mode 100644 index 0000000..2ac24fb --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + + + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.storedprocedure.async; + +import com.azure.cosmos.*; +import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; +import com.azure.cosmos.examples.common.AccountSettings; +import com.azure.cosmos.examples.common.CustomPOJO; +import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.UUID; +import java.util.concurrent.CountDownLatch; + +public class SampleStoredProcedureAsync { + + private CosmosAsyncClient client; + + private final String databaseName = "SprocTestDB"; + private final String containerName = "SprocTestContainer"; + + private CosmosAsyncDatabase database; + private CosmosAsyncContainer container; + + private String sprocId; + + protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); + + public void close() { + client.close(); + } + + /** + * Run a Hello CosmosDB console application. + * + * @param args command line args. + */ + //
+ public static void main(String[] args) { + SampleStoredProcedureAsync p = new SampleStoredProcedureAsync(); + + try { + p.sprocDemo(); + System.out.println("Demo complete, please hold while resources are released"); + p.shutdown(); + System.out.println("Done.\n"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println(String.format("Cosmos getStarted failed with %s", e)); + p.close(); + } finally { + } + } + + //
+ + private void sprocDemo() throws Exception { + //Setup client, DB, and the container for which we will create stored procedures + //The container partition key will be id + setUp(); + + //Create stored procedure and list all stored procedures that have been created. + createStoredProcedure(); + readAllSprocs(); + + //Execute the stored procedure, which we expect will create an item with id test_doc + executeStoredProcedure(); + + //Perform a point-read to confirm that the item with id test_doc exists + System.out.println("Checking that a document was created by the stored procedure..."); + CosmosAsyncItemResponse test_resp = + container.readItem("test_doc",new PartitionKey("test_doc"),CustomPOJO.class).block(); + System.out.println(String.format( + "Status return value of point-read for document created by stored procedure (200 indicates success): %d",test_resp.getStatusCode())); + } + + public void setUp() throws Exception{ + System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + + ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); + // Setting the preferred location to Cosmos DB Account region + // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application + defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); + + // Create sync client + // + client = new CosmosClientBuilder() + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildAsyncClient(); + + System.out.println("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n"); + + client.createDatabaseIfNotExists(databaseName).flatMap(databaseResponse -> { + database = databaseResponse.getDatabase(); + return Mono.empty(); + }).block(); + + CosmosContainerProperties containerProperties = + new CosmosContainerProperties(containerName, "/id"); + database.createContainerIfNotExists(containerProperties, 400).flatMap(containerResponse -> { + container = containerResponse.getContainer(); + return Mono.empty(); + }).block(); + } + + public void shutdown() throws Exception { + //Safe clean & close + deleteStoredProcedure(); + } + + public void createStoredProcedure() throws Exception { + System.out.println("Creating stored procedure...\n"); + + sprocId = "createMyDocument"; + String sprocBody = "function createMyDocument() {\n" + + "var documentToCreate = {\"id\":\"test_doc\"}\n" + + "var context = getContext();\n" + + "var collection = context.getCollection();\n" + + "var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" + + " function (err, documentCreated) {\n" + + "if (err) throw new Error('Error' + err.message);\n" + + "context.getResponse().setBody(documentCreated.id)\n" + + "});\n" + + "if (!accepted) return;\n" + + "}"; + CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId,sprocBody); + container.getScripts() + .createStoredProcedure(storedProcedureDef, + new CosmosStoredProcedureRequestOptions()).block(); + } + + private void readAllSprocs() throws Exception { + + FeedOptions feedOptions = new FeedOptions(); + CosmosContinuablePagedFlux fluxResponse = + container.getScripts().readAllStoredProcedures(feedOptions); + + final CountDownLatch completionLatch = new CountDownLatch(1); + + + + fluxResponse.flatMap(storedProcedureProperties -> { + System.out.println(String.format("Stored Procedure: %s\n",storedProcedureProperties.getId())); + return Mono.empty(); + }).subscribe( + s -> {}, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException)err; + cerr.printStackTrace(); + System.out.println(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> {completionLatch.countDown();} + ); + + completionLatch.await(); + } + + public void executeStoredProcedure() throws Exception { + System.out.println(String.format("Executing stored procedure %s...\n\n",sprocId)); + + CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions(); + options.setPartitionKey(new PartitionKey("test_doc")); + + container.getScripts() + .getStoredProcedure(sprocId) + .execute(null, options) + .flatMap(executeResponse -> { + System.out.println(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", + sprocId, + executeResponse.getResponseAsString(), + executeResponse.getStatusCode(), + executeResponse.getRequestCharge())); + return Mono.empty(); + }).block(); + } + + public void deleteStoredProcedure() throws Exception { + System.out.println("-Deleting stored procedure...\n"); + container.getScripts() + .getStoredProcedure(sprocId) + .delete().block(); + System.out.println("-Deleting database...\n"); + database.delete().block(); + System.out.println("-Closing client instance...\n"); + client.close(); + } +} diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java new file mode 100644 index 0000000..fe96c54 --- /dev/null +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.examples.storedprocedure.sync; + +import com.azure.cosmos.*; +import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; +import com.azure.cosmos.examples.common.AccountSettings; +import com.azure.cosmos.examples.common.CustomPOJO; +import com.azure.cosmos.implementation.Utils; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.UUID; +import java.util.Iterator; + +public class SampleStoredProcedure { + + private CosmosClient client; + + private final String databaseName = "SprocTestDB"; + private final String containerName = "SprocTestContainer"; + + private CosmosDatabase database; + private CosmosContainer container; + + private String sprocId; + + protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); + + public void close() { + client.close(); + } + + /** + * Run a Hello CosmosDB console application. + * + * @param args command line args. + */ + //
+ public static void main(String[] args) { + SampleStoredProcedure p = new SampleStoredProcedure(); + + try { + p.sprocDemo(); + System.out.println("Demo complete, please hold while resources are released"); + p.shutdown(); + System.out.println("Done.\n"); + } catch (Exception e) { + e.printStackTrace(); + System.err.println(String.format("Cosmos getStarted failed with %s", e)); + p.close(); + } finally { + } + } + + //
+ + private void sprocDemo() throws Exception { + //Setup client, DB, and the container for which we will create stored procedures + //The container partition key will be id + setUp(); + + //Create stored procedure and list all stored procedures that have been created. + createStoredProcedure(); + readAllSprocs(); + + //Execute the stored procedure, which we expect will create an item with id test_doc + executeStoredProcedure(); + + //Perform a point-read to confirm that the item with id test_doc exists + System.out.println("Checking that a document was created by the stored procedure..."); + CosmosItemResponse test_resp = container.readItem("test_doc",new PartitionKey("test_doc"),CustomPOJO.class); + System.out.println(String.format( + "Result of point-read for document created by stored procedure (200 indicates success): %d",test_resp.getStatusCode())); + } + + public void setUp() throws Exception{ + System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + + ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); + // Setting the preferred location to Cosmos DB Account region + // West US is just an example. User should set preferred location to the Cosmos DB region closest to the application + defaultPolicy.setPreferredLocations(Lists.newArrayList("West US")); + + // Create sync client + // + client = new CosmosClientBuilder() + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildClient(); + + System.out.println("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n"); + + database = client.createDatabaseIfNotExists(databaseName).getDatabase(); + + CosmosContainerProperties containerProperties = + new CosmosContainerProperties(containerName, "/id"); + container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); + } + + public void shutdown() throws Exception { + //Safe clean & close + deleteStoredProcedure(); + } + + public void createStoredProcedure() throws Exception { + System.out.println("Creating stored procedure..."); + + sprocId = "createMyDocument"; + String sprocBody = "function createMyDocument() {\n" + + "var documentToCreate = {\"id\":\"test_doc\"}\n" + + "var context = getContext();\n" + + "var collection = context.getCollection();\n" + + "var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" + + " function (err, documentCreated) {\n" + + "if (err) throw new Error('Error' + err.message);\n" + + "context.getResponse().setBody(documentCreated.id)\n" + + "});\n" + + "if (!accepted) return;\n" + + "}"; + CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId,sprocBody); + container.getScripts() + .createStoredProcedure(storedProcedureDef, + new CosmosStoredProcedureRequestOptions()); + } + + private void readAllSprocs() throws Exception { + System.out.println("Listing all stored procedures associated with container " + containerName + "\n"); + + FeedOptions feedOptions = new FeedOptions(); + CosmosContinuablePagedIterable feedResponseIterable = + container.getScripts().readAllStoredProcedures(feedOptions); + + Iterator feedResponseIterator = feedResponseIterable.iterator(); + + while(feedResponseIterator.hasNext()) { + CosmosStoredProcedureProperties storedProcedureProperties = feedResponseIterator.next(); + System.out.println(String.format("Stored Procedure: %s",storedProcedureProperties)); + } + } + + public void executeStoredProcedure() throws Exception { + System.out.println(String.format("Executing stored procedure %s...\n\n",sprocId)); + + CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions(); + options.setPartitionKey(new PartitionKey("test_doc")); + CosmosStoredProcedureResponse executeResponse = container.getScripts() + .getStoredProcedure(sprocId) + .execute(null, options); + + System.out.println(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", + sprocId, + executeResponse.responseAsString(), + executeResponse.getStatusCode(), + executeResponse.getRequestCharge())); + } + + public void deleteStoredProcedure() throws Exception { + System.out.println("-Deleting stored procedure...\n"); + container.getScripts() + .getStoredProcedure(sprocId) + .delete(); + System.out.println("-Deleting database...\n"); + database.delete(); + System.out.println("-Closing client instance...\n"); + client.close(); + System.out.println("Done."); + } +} diff --git a/src/main/resources/log4j2.properties b/src/main/resources/log4j2.properties new file mode 100644 index 0000000..43f940f --- /dev/null +++ b/src/main/resources/log4j2.properties @@ -0,0 +1,21 @@ +# this is the log4j configuration for tests + +# Set root logger level to WARN and its appender to STDOUT. +rootLogger.level = INFO +rootLogger.appenderRef.stdout.ref = STDOUT + +logger.netty.name = io.netty +logger.netty.level = INFO + +logger.reactor.name = io.reactivex +logger.reactor.level = INFO + +logger.cosmos.name = com.azure.cosmos +logger.cosmos.level = INFO + +# STDOUT is a ConsoleAppender and uses PatternLayout. +appender.console.name = STDOUT +appender.console.type = Console +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %m%n + diff --git a/src/main/resources/multi-master-sample-config.properties b/src/main/resources/multi-master-sample-config.properties new file mode 100644 index 0000000..42c2030 --- /dev/null +++ b/src/main/resources/multi-master-sample-config.properties @@ -0,0 +1,8 @@ +endpoint= +key= +regions=North Central US;North Europe;Southeast Asia +databaseName=multiMasterDemoDB +manualCollectionName=myManualCollection +lwwCollectionName=myLwwCollection +udpCollectionName=myUdpCollection +basicCollectionName=myBasicCollection \ No newline at end of file diff --git a/src/main/resources/resolver-storedproc.txt b/src/main/resources/resolver-storedproc.txt new file mode 100644 index 0000000..e856721 --- /dev/null +++ b/src/main/resources/resolver-storedproc.txt @@ -0,0 +1,45 @@ +function resolver(incomingRecord, existingRecord, isTombstone, conflictingRecords) { + var collection = getContext().getCollection(); + if (!incomingRecord) { + if (existingRecord) { + collection.deleteDocument(existingRecord._self, {}, function(err, responseOptions) { + if (err) throw err; + }); + } + } else if (isTombstone) { + // delete always wins. + } else { + var documentToUse = incomingRecord; + if (existingRecord) { + if (documentToUse.regionId < existingRecord.regionId) { + documentToUse = existingRecord; + } + } + var i; + for (i = 0; i < conflictingRecords.length; i++) { + if (documentToUse.regionId < conflictingRecords[i].regionId) { + documentToUse = conflictingRecords[i]; + } + } + tryDelete(conflictingRecords, incomingRecord, existingRecord, documentToUse); + } + function tryDelete(documents, incoming, existing, documentToInsert) { + if (documents.length > 0) { + collection.deleteDocument(documents[0]._self, {}, function(err, responseOptions) { + if (err) throw err; + documents.shift(); + tryDelete(documents, incoming, existing, documentToInsert); + }); + } else if (existing) { + collection.replaceDocument(existing._self, documentToInsert, + function(err, documentCreated) { + if (err) throw err; + }); + } else { + collection.createDocument(collection.getSelfLink(), documentToInsert, + function(err, documentCreated) { + if (err) throw err; + }); + } + } +} \ No newline at end of file From c3f0847c11c76bee79d8f27b7f1a76659c2385a1 Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Mon, 9 Mar 2020 18:15:48 -0700 Subject: [PATCH 04/11] Updated pom.xml to latest release --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 57eb621..2c82b79 100644 --- a/pom.xml +++ b/pom.xml @@ -77,7 +77,7 @@ com.azure azure-cosmos - 4.0.0-preview.2 + 4.0.1-beta.1 \ No newline at end of file From 5eb8c47317c18488eb2f39390738d5c70a2a8380 Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Tue, 10 Mar 2020 10:17:48 -0700 Subject: [PATCH 05/11] Fixed pom.xml and modified CRUD quickstart --- pom.xml | 19 +------------------ .../sync/SampleCRUDQuickstart.java | 2 +- 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/pom.xml b/pom.xml index 2c82b79..461ff84 100644 --- a/pom.xml +++ b/pom.xml @@ -11,24 +11,7 @@ UTF-8 - - - azure-sdk-for-java - https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 - - - - - azure-sdk-for-java - https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 - - true - - - true - - - + diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java index 293cd35..5bb48ab 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java @@ -56,7 +56,7 @@ public static void main(String[] args) { SampleCRUDQuickstart p = new SampleCRUDQuickstart(); try { - System.out.println("Starting SYNC main"); + logger.info("Starting SYNC main"); p.getStartedDemo(); System.out.println("Demo complete, please hold while resources are released"); } catch (Exception e) { From 7db028a3cf7c0572e1b06b430b783e1b7668a1a0 Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Tue, 10 Mar 2020 10:52:26 -0700 Subject: [PATCH 06/11] Manually merged fixes from master: pom.xml fix given latest 4.0.1-beta.1 jar; updated samples for new jar --- pom.xml | 14 ----------- .../changefeed/SampleChangeFeedProcessor.java | 6 ++--- .../async/SampleCRUDQuickstartAsync.java | 11 +++++---- .../sync/SampleCRUDQuickstart.java | 23 +++++-------------- .../async/SampleIndexManagementAsync.java | 11 +++++---- .../sync/SampleIndexManagement.java | 7 +++--- .../async/SampleStoredProcedureAsync.java | 4 ++-- .../sync/SampleStoredProcedure.java | 6 ++--- 8 files changed, 29 insertions(+), 53 deletions(-) diff --git a/pom.xml b/pom.xml index 461ff84..5cd487f 100644 --- a/pom.xml +++ b/pom.xml @@ -27,20 +27,6 @@ org.codehaus.mojo exec-maven-plugin 1.6.0 - - - sync - - com.azure.cosmos.sample.sync.SyncMain - - - - async - - com.azure.cosmos.sample.async.AsyncMain - - - org.apache.maven.plugins diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java index c83cb82..f667334 100644 --- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java +++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java @@ -6,15 +6,15 @@ import com.azure.cosmos.ConnectionPolicy; import com.azure.cosmos.ConsistencyLevel; import com.azure.cosmos.CosmosAsyncContainer; -import com.azure.cosmos.CosmosAsyncContainerResponse; import com.azure.cosmos.CosmosAsyncDatabase; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.CosmosClientException; -import com.azure.cosmos.CosmosContainerProperties; -import com.azure.cosmos.CosmosContainerRequestOptions; import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.examples.common.CustomPOJO; import com.azure.cosmos.implementation.Utils; +import com.azure.cosmos.models.CosmosAsyncContainerResponse; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.CosmosContainerRequestOptions; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java index 3e5b581..58618a3 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java @@ -9,6 +9,7 @@ import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.Families; import com.azure.cosmos.examples.common.Family; +import com.azure.cosmos.models.*; import com.google.common.collect.Lists; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -170,7 +171,7 @@ private void createFamilies(Flux families) throws Exception { System.out.println(String.format("Created item with request charge of %.2f within" + " duration %s", itemResponse.getRequestCharge(), itemResponse.getRequestLatency())); - System.out.println(String.format("Item ID: %s\n", itemResponse.getResource().getId())); + System.out.println(String.format("Item ID: %s\n", itemResponse.getItem().getId())); return Mono.just(itemResponse.getRequestCharge()); }) //Flux of request charges .reduce(0.0, @@ -238,7 +239,7 @@ private void readItems(Flux familiesToCreate) { double requestCharge = itemResponse.getRequestCharge(); Duration requestLatency = itemResponse.getRequestLatency(); System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", - itemResponse.getResource().getId(), requestCharge, requestLatency)); + itemResponse.getItem().getId(), requestCharge, requestLatency)); }, err -> { if (err instanceof CosmosClientException) { @@ -270,12 +271,12 @@ private void queryItems() { // Set some common query options FeedOptions queryOptions = new FeedOptions(); - queryOptions.maxItemCount(10); + queryOptions.setMaxItemCount(10); //queryOptions.setEnableCrossPartitionQuery(true); //No longer needed in SDK v4 // Set populate query metrics to get metrics around query executions - queryOptions.populateQueryMetrics(true); + queryOptions.setPopulateQueryMetrics(true); - CosmosContinuablePagedFlux pagedFluxResponse = container.queryItems( + CosmosPagedFlux pagedFluxResponse = container.queryItems( "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); final CountDownLatch completionLatch = new CountDownLatch(1); diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java index 5bb48ab..9d3d827 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java @@ -3,23 +3,12 @@ package com.azure.cosmos.examples.crudquickstart.sync; -import com.azure.cosmos.ConnectionPolicy; -import com.azure.cosmos.ConsistencyLevel; -import com.azure.cosmos.CosmosClient; -import com.azure.cosmos.CosmosClientBuilder; -import com.azure.cosmos.CosmosClientException; -import com.azure.cosmos.CosmosContainer; -import com.azure.cosmos.CosmosContainerProperties; -import com.azure.cosmos.CosmosContinuablePagedIterable; -import com.azure.cosmos.CosmosDatabase; -import com.azure.cosmos.CosmosItemRequestOptions; -import com.azure.cosmos.CosmosItemResponse; -import com.azure.cosmos.FeedOptions; -import com.azure.cosmos.PartitionKey; +import com.azure.cosmos.*; import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.Families; import com.azure.cosmos.examples.common.Family; +import com.azure.cosmos.models.*; import com.google.common.collect.Lists; import java.time.Duration; @@ -56,7 +45,7 @@ public static void main(String[] args) { SampleCRUDQuickstart p = new SampleCRUDQuickstart(); try { - logger.info("Starting SYNC main"); + System.out.println("Starting SYNC main"); p.getStartedDemo(); System.out.println("Demo complete, please hold while resources are released"); } catch (Exception e) { @@ -204,12 +193,12 @@ private void queryItems() { // // Set some common query options FeedOptions queryOptions = new FeedOptions(); - queryOptions.maxItemCount(10); + queryOptions.setMaxItemCount(10); //queryOptions.setEnableCrossPartitionQuery(true); //No longer necessary in SDK v4 // Set populate query metrics to get metrics around query executions - queryOptions.populateQueryMetrics(true); + queryOptions.setPopulateQueryMetrics(true); - CosmosContinuablePagedIterable familiesPagedIterable = container.queryItems( + CosmosPagedIterable familiesPagedIterable = container.queryItems( "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); familiesPagedIterable.iterableByPage().forEach(cosmosItemPropertiesFeedResponse -> { diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java index b335434..7d5e5ea 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java @@ -8,6 +8,7 @@ import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.Families; import com.azure.cosmos.examples.common.Family; +import com.azure.cosmos.models.*; import com.google.common.collect.Lists; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -218,7 +219,7 @@ private void createFamilies(Flux families) throws Exception { System.out.println(String.format("Created item with request charge of %.2f within" + " duration %s", itemResponse.getRequestCharge(), itemResponse.getRequestLatency())); - System.out.println(String.format("Item ID: %s\n", itemResponse.getResource().getId())); + System.out.println(String.format("Item ID: %s\n", itemResponse.getItem().getId())); return Mono.just(itemResponse.getRequestCharge()); }) //Flux of request charges .reduce(0.0, @@ -269,7 +270,7 @@ private void readItems(Flux familiesToCreate) { double requestCharge = itemResponse.getRequestCharge(); Duration requestLatency = itemResponse.getRequestLatency(); System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", - itemResponse.getResource().getId(), requestCharge, requestLatency)); + itemResponse.getItem().getId(), requestCharge, requestLatency)); }, err -> { if (err instanceof CosmosClientException) { @@ -301,11 +302,11 @@ private void queryItems() { // Set some common query options FeedOptions queryOptions = new FeedOptions(); - queryOptions.maxItemCount(10); + queryOptions.setMaxItemCount(10); // Set populate query metrics to get metrics around query executions - queryOptions.populateQueryMetrics(true); + queryOptions.setPopulateQueryMetrics(true); - CosmosContinuablePagedFlux pagedFluxResponse = container.queryItems( + CosmosPagedFlux pagedFluxResponse = container.queryItems( "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); final CountDownLatch completionLatch = new CountDownLatch(1); diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java index fc07cab..1b459df 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java @@ -8,6 +8,7 @@ import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.Families; import com.azure.cosmos.examples.common.Family; +import com.azure.cosmos.models.*; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -231,11 +232,11 @@ private void queryItems() { // // Set some common query options FeedOptions queryOptions = new FeedOptions(); - queryOptions.maxItemCount(10); + queryOptions.setMaxItemCount(10); // Set populate query metrics to get metrics around query executions - queryOptions.populateQueryMetrics(true); + queryOptions.setPopulateQueryMetrics(true); - CosmosContinuablePagedIterable familiesPagedIterable = container.queryItems( + CosmosPagedIterable familiesPagedIterable = container.queryItems( "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); familiesPagedIterable.iterableByPage().forEach(cosmosItemPropertiesFeedResponse -> { diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java index 2ac24fb..eaf23bb 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java @@ -12,10 +12,10 @@ import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.CustomPOJO; +import com.azure.cosmos.models.*; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.UUID; @@ -144,7 +144,7 @@ public void createStoredProcedure() throws Exception { private void readAllSprocs() throws Exception { FeedOptions feedOptions = new FeedOptions(); - CosmosContinuablePagedFlux fluxResponse = + CosmosPagedFlux fluxResponse = container.getScripts().readAllStoredProcedures(feedOptions); final CountDownLatch completionLatch = new CountDownLatch(1); diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java index fe96c54..4524507 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java @@ -7,13 +7,11 @@ import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.CustomPOJO; -import com.azure.cosmos.implementation.Utils; -import com.fasterxml.jackson.databind.ObjectMapper; +import com.azure.cosmos.models.*; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.UUID; import java.util.Iterator; public class SampleStoredProcedure { @@ -133,7 +131,7 @@ private void readAllSprocs() throws Exception { System.out.println("Listing all stored procedures associated with container " + containerName + "\n"); FeedOptions feedOptions = new FeedOptions(); - CosmosContinuablePagedIterable feedResponseIterable = + CosmosPagedIterable feedResponseIterable = container.getScripts().readAllStoredProcedures(feedOptions); Iterator feedResponseIterator = feedResponseIterable.iterator(); From 4b1d76b086f80e1c74e41e91151b45fc18ba9938 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Tue, 10 Mar 2020 11:05:48 -0700 Subject: [PATCH 07/11] Fixed logging --- pom.xml | 112 +++++++++++++++++++++++++++++++++----------------------- 1 file changed, 66 insertions(+), 46 deletions(-) diff --git a/pom.xml b/pom.xml index 5cd487f..d11e9c8 100644 --- a/pom.xml +++ b/pom.xml @@ -1,52 +1,72 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.azure - azure-cosmos-java-sql-api-samples - 1.0-SNAPSHOT - Get Started With Sync / Async Java SDK for SQL API of Azure Cosmos DB Database Service - - UTF-8 - + com.azure + azure-cosmos-java-sql-api-samples + 1.0-SNAPSHOT + Get Started With Sync / Async Java SDK for SQL API of Azure Cosmos DB Database Service + + + UTF-8 + - - - - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - - - org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 - - - - - - - - - com.azure - azure-cosmos - 4.0.1-beta.1 - - + + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.8 + + + + org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 + + + + + + + + + com.azure + azure-cosmos + 4.0.1-beta.1 + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.13.0 + test + + + + org.apache.logging.log4j + log4j-api + 2.11.1 + test + + + + org.slf4j + slf4j-jdk14 + 1.7.28 + + \ No newline at end of file From 07ebbf4d234643a158fce70658dba891713ec13e Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Tue, 10 Mar 2020 11:34:40 -0700 Subject: [PATCH 08/11] Slight modification to log4j2 properties; fixed import formatting --- .../changefeed/SampleChangeFeedProcessor.java | 2 +- .../async/SampleCRUDQuickstartAsync.java | 21 +++++-- .../sync/SampleCRUDQuickstart.java | 56 +++++++++++-------- .../async/SampleIndexManagementAsync.java | 25 +++++++-- .../sync/SampleIndexManagement.java | 20 ++++++- .../async/SampleStoredProcedureAsync.java | 17 +++++- .../sync/SampleStoredProcedure.java | 16 +++++- src/main/resources/log4j2.properties | 3 - 8 files changed, 115 insertions(+), 45 deletions(-) diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java index f667334..aa3b629 100644 --- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java +++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java @@ -5,11 +5,11 @@ import com.azure.cosmos.ChangeFeedProcessor; import com.azure.cosmos.ConnectionPolicy; import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosAsyncDatabase; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.CosmosClientException; -import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.examples.common.CustomPOJO; import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.models.CosmosAsyncContainerResponse; diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java index 58618a3..42d604d 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java @@ -4,13 +4,27 @@ package com.azure.cosmos.examples.crudquickstart.async; -import com.azure.cosmos.*; +import com.azure.cosmos.ConnectionPolicy; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosAsyncContainer; +import com.azure.cosmos.CosmosAsyncDatabase; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosClientException; +import com.azure.cosmos.CosmosPagedFlux; import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.Families; import com.azure.cosmos.examples.common.Family; -import com.azure.cosmos.models.*; +import com.azure.cosmos.models.CosmosAsyncContainerResponse; +import com.azure.cosmos.models.CosmosAsyncDatabaseResponse; +import com.azure.cosmos.models.CosmosAsyncItemResponse; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.FeedOptions; +import com.azure.cosmos.models.PartitionKey; import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -18,9 +32,6 @@ import java.util.concurrent.CountDownLatch; import java.util.stream.Collectors; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class SampleCRUDQuickstartAsync { private CosmosAsyncClient client; diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java index 9d3d827..bbcf0ec 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java @@ -3,22 +3,32 @@ package com.azure.cosmos.examples.crudquickstart.sync; -import com.azure.cosmos.*; +import com.azure.cosmos.ConnectionPolicy; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosClientException; +import com.azure.cosmos.CosmosContainer; +import com.azure.cosmos.CosmosDatabase; +import com.azure.cosmos.CosmosPagedIterable; import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.Families; import com.azure.cosmos.examples.common.Family; -import com.azure.cosmos.models.*; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.CosmosItemRequestOptions; +import com.azure.cosmos.models.CosmosItemResponse; +import com.azure.cosmos.models.FeedOptions; +import com.azure.cosmos.models.PartitionKey; import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class SampleCRUDQuickstart { private CosmosClient client; @@ -45,7 +55,7 @@ public static void main(String[] args) { SampleCRUDQuickstart p = new SampleCRUDQuickstart(); try { - System.out.println("Starting SYNC main"); + logger.info("Starting SYNC main"); p.getStartedDemo(); System.out.println("Demo complete, please hold while resources are released"); } catch (Exception e) { @@ -79,11 +89,11 @@ private void getStartedDemo() throws Exception { // Create sync client // client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildClient(); + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildClient(); // @@ -128,7 +138,7 @@ private void createContainerIfNotExists() throws Exception { // Create container if not exists // CosmosContainerProperties containerProperties = - new CosmosContainerProperties(containerName, "/lastName"); + new CosmosContainerProperties(containerName, "/lastName"); // Create container with 400 RU/s container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); @@ -152,15 +162,15 @@ private void createFamilies(List families) throws Exception { // Get request charge and other properties like latency, and diagnostics strings, etc. System.out.println(String.format("Created item with request charge of %.2f within duration %s", - item.getRequestCharge(), item.getRequestLatency())); + item.getRequestCharge(), item.getRequestLatency())); totalRequestCharge += item.getRequestCharge(); } System.out.println(String.format("Created %d items with total request charge of %.2f", - families.size(), totalRequestCharge)); + families.size(), totalRequestCharge)); Family family_to_upsert = families.get(0); - System.out.println(String.format("Upserting the item with id %s after modifying the isRegistered field...",family_to_upsert.getId())); + System.out.println(String.format("Upserting the item with id %s after modifying the isRegistered field...", family_to_upsert.getId())); family_to_upsert.setRegistered(!family_to_upsert.isRegistered()); CosmosItemResponse item = container.upsertItem(family_to_upsert); @@ -180,7 +190,7 @@ private void readItems(ArrayList familiesToCreate) { double requestCharge = item.getRequestCharge(); Duration requestLatency = item.getRequestLatency(); System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", - item.getResource().getId(), requestCharge, requestLatency)); + item.getResource().getId(), requestCharge, requestLatency)); } catch (CosmosClientException e) { e.printStackTrace(); System.out.println(String.format("Read Item failed with %s", e)); @@ -203,20 +213,20 @@ private void queryItems() { familiesPagedIterable.iterableByPage().forEach(cosmosItemPropertiesFeedResponse -> { System.out.println("Got a page of query result with " + - cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)" - + " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()); + cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)" + + " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()); System.out.println("Item Ids " + cosmosItemPropertiesFeedResponse - .getResults() - .stream() - .map(Family::getId) - .collect(Collectors.toList())); + .getResults() + .stream() + .map(Family::getId) + .collect(Collectors.toList())); }); // } private void deleteItem(Family item) { - container.deleteItem(item.getId(),new PartitionKey(item.getLastName()),new CosmosItemRequestOptions()); + container.deleteItem(item.getId(), new PartitionKey(item.getLastName()), new CosmosItemRequestOptions()); } private void shutdown() { diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java index 7d5e5ea..2419daf 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java @@ -3,13 +3,31 @@ package com.azure.cosmos.examples.indexmanagement.async; -import com.azure.cosmos.*; +import com.azure.cosmos.ConnectionPolicy; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosAsyncContainer; +import com.azure.cosmos.CosmosAsyncDatabase; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosClientException; +import com.azure.cosmos.CosmosPagedFlux; import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.Families; import com.azure.cosmos.examples.common.Family; -import com.azure.cosmos.models.*; +import com.azure.cosmos.models.CosmosAsyncContainerResponse; +import com.azure.cosmos.models.CosmosAsyncDatabaseResponse; +import com.azure.cosmos.models.CosmosAsyncItemResponse; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.ExcludedPath; +import com.azure.cosmos.models.FeedOptions; +import com.azure.cosmos.models.IncludedPath; +import com.azure.cosmos.models.IndexingMode; +import com.azure.cosmos.models.IndexingPolicy; +import com.azure.cosmos.models.PartitionKey; import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -19,9 +37,6 @@ import java.util.concurrent.CountDownLatch; import java.util.stream.Collectors; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class SampleIndexManagementAsync { private CosmosAsyncClient client; diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java index 1b459df..2ed1f4d 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java @@ -3,19 +3,33 @@ package com.azure.cosmos.examples.indexmanagement.sync; -import com.azure.cosmos.*; +import com.azure.cosmos.ConnectionPolicy; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosClientException; +import com.azure.cosmos.CosmosContainer; +import com.azure.cosmos.CosmosDatabase; +import com.azure.cosmos.CosmosPagedIterable; import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.Families; import com.azure.cosmos.examples.common.Family; -import com.azure.cosmos.models.*; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.CosmosItemRequestOptions; +import com.azure.cosmos.models.CosmosItemResponse; +import com.azure.cosmos.models.ExcludedPath; +import com.azure.cosmos.models.FeedOptions; +import com.azure.cosmos.models.IncludedPath; +import com.azure.cosmos.models.IndexingMode; +import com.azure.cosmos.models.IndexingPolicy; +import com.azure.cosmos.models.PartitionKey; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java index eaf23bb..f0953da 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java @@ -8,17 +8,28 @@ package com.azure.cosmos.examples.storedprocedure.async; -import com.azure.cosmos.*; +import com.azure.cosmos.ConnectionPolicy; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosAsyncContainer; +import com.azure.cosmos.CosmosAsyncDatabase; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosClientException; +import com.azure.cosmos.CosmosPagedFlux; import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.CustomPOJO; -import com.azure.cosmos.models.*; +import com.azure.cosmos.models.CosmosAsyncItemResponse; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.CosmosStoredProcedureProperties; +import com.azure.cosmos.models.CosmosStoredProcedureRequestOptions; +import com.azure.cosmos.models.FeedOptions; +import com.azure.cosmos.models.PartitionKey; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; -import java.util.UUID; import java.util.concurrent.CountDownLatch; public class SampleStoredProcedureAsync { diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java index 4524507..b4d0e4b 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java @@ -3,11 +3,23 @@ package com.azure.cosmos.examples.storedprocedure.sync; -import com.azure.cosmos.*; +import com.azure.cosmos.ConnectionPolicy; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosContainer; +import com.azure.cosmos.CosmosDatabase; +import com.azure.cosmos.CosmosPagedIterable; import com.azure.cosmos.examples.changefeed.SampleChangeFeedProcessor; import com.azure.cosmos.examples.common.AccountSettings; import com.azure.cosmos.examples.common.CustomPOJO; -import com.azure.cosmos.models.*; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.CosmosItemResponse; +import com.azure.cosmos.models.CosmosStoredProcedureProperties; +import com.azure.cosmos.models.CosmosStoredProcedureRequestOptions; +import com.azure.cosmos.models.CosmosStoredProcedureResponse; +import com.azure.cosmos.models.FeedOptions; +import com.azure.cosmos.models.PartitionKey; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/resources/log4j2.properties b/src/main/resources/log4j2.properties index 43f940f..fccb3cc 100644 --- a/src/main/resources/log4j2.properties +++ b/src/main/resources/log4j2.properties @@ -7,9 +7,6 @@ rootLogger.appenderRef.stdout.ref = STDOUT logger.netty.name = io.netty logger.netty.level = INFO -logger.reactor.name = io.reactivex -logger.reactor.level = INFO - logger.cosmos.name = com.azure.cosmos logger.cosmos.level = INFO From c846111d588ba97e578a0f4c7aa933b683faa6cc Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Tue, 10 Mar 2020 11:59:28 -0700 Subject: [PATCH 09/11] Pulling in master, in which the previous two commits were applied manually and also other improvements were made. --- README.md | 18 +- pom.xml | 124 ++++----- .../changefeed/SampleChangeFeedProcessor.java | 85 +++--- .../changefeed/SampleConfigurations.java | 16 +- .../examples/common/AccountSettings.java | 4 +- .../cosmos/examples/common/CustomPOJO.java | 5 +- .../cosmos/examples/common/Families.java | 10 +- .../async/SampleCRUDQuickstartAsync.java | 244 +++++++++--------- .../sync/SampleCRUDQuickstart.java | 50 ++-- .../async/SampleIndexManagementAsync.java | 86 +++--- .../sync/SampleIndexManagement.java | 46 ++-- .../async/SampleStoredProcedureAsync.java | 143 +++++----- .../sync/SampleStoredProcedure.java | 124 ++++----- src/main/resources/log4j2.properties | 24 +- 14 files changed, 495 insertions(+), 484 deletions(-) diff --git a/README.md b/README.md index 219c639..4162be7 100644 --- a/README.md +++ b/README.md @@ -59,17 +59,17 @@ which gives the sample read/write access to your account. To choose which sample will run, populate the **Main class** field of the Configuration with ``` -com.azure.cosmos.examples.changefeed.sample +com.azure.cosmos.examples.sample.synchronicity.MainClass ``` -where *sample* can be -* SampleCRUDQuickstart -* SampleCRUDQuickstartAsync -* SampleIndexManagement -* SampleIndexManagementAsync -* SampleStoredProcedure -* SampleStoredProcedureAsync -* SampleChangeFeedProcessor +where *sample.synchronicity.MainClass* can be +* crudquickstart.sync.SampleCRUDQuickstart +* crudquickstart.async.SampleCRUDQuickstartAsync +* indexmanagement.sync.SampleIndexManagement +* indexmanagement.async.SampleIndexManagementAsync +* storedprocedure.sync.SampleStoredProcedure +* storedprocedure.async.SampleStoredProcedureAsync +* changefeed.SampleChangeFeedProcessor *(Changefeed has only an async sample, no sync sample.)* *Build and execute from command line without an IDE:* From top-level directory of repo: ``` diff --git a/pom.xml b/pom.xml index d11e9c8..69ece04 100644 --- a/pom.xml +++ b/pom.xml @@ -2,71 +2,71 @@ - 4.0.0 + 4.0.0 - com.azure - azure-cosmos-java-sql-api-samples - 1.0-SNAPSHOT - Get Started With Sync / Async Java SDK for SQL API of Azure Cosmos DB Database Service - - - UTF-8 - + com.azure + azure-cosmos-java-sql-api-samples + 1.0-SNAPSHOT + Get Started With Sync / Async Java SDK for SQL API of Azure Cosmos DB Database Service + + + UTF-8 + - - - - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - - - org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 - - - - - - - - - com.azure - azure-cosmos - 4.0.1-beta.1 - - - org.apache.logging.log4j - log4j-slf4j-impl - 2.13.0 - test - + + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.8 + + + + org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 + + + + + + + + + com.azure + azure-cosmos + 4.0.1-beta.1 + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.13.0 + test + - - org.apache.logging.log4j - log4j-api - 2.11.1 - test - + + org.apache.logging.log4j + log4j-api + 2.11.1 + test + - - org.slf4j - slf4j-jdk14 - 1.7.28 - - + + org.slf4j + slf4j-jdk14 + 1.7.28 + + \ No newline at end of file diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java index aa3b629..5a28566 100644 --- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java +++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java @@ -28,7 +28,6 @@ /** * Sample for Change Feed Processor. - * */ public class SampleChangeFeedProcessor { @@ -42,7 +41,7 @@ public class SampleChangeFeedProcessor { private static ChangeFeedProcessor changeFeedProcessorInstance; private static boolean isWorkCompleted = false; - public static void main (String[]args) { + public static void main(String[] args) { logger.info("BEGIN Sample"); try { @@ -56,16 +55,16 @@ public static void main (String[]args) { //Summary of the next four commands: //-Create an asynchronous Azure Cosmos DB client and database so that we can issue async requests to the DB //-Create a "feed container" and a "lease container" in the DB - System.out.println("-->CREATE DocumentClient"); + logger.info("-->CREATE DocumentClient"); CosmosAsyncClient client = getCosmosClient(); - System.out.println("-->CREATE sample's database: " + DATABASE_NAME); + logger.info("-->CREATE sample's database: " + DATABASE_NAME); CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME); - System.out.println("-->CREATE container for documents: " + COLLECTION_NAME); + logger.info("-->CREATE container for documents: " + COLLECTION_NAME); CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME); - System.out.println("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); + logger.info("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); //Model of a worker thread or application which leases access to monitor one or more feed container @@ -73,17 +72,17 @@ public static void main (String[]args) { //The next line causes the worker to create and start an instance of the Change Feed Processor. See the implementation of getChangeFeedProcessor() for guidance //on creating a handler for Change Feed events. In this stream, we also trigger the insertion of 10 documents on a separate //thread. - System.out.println("-->START Change Feed Processor on worker (handles changes asynchronously)"); + logger.info("-->START Change Feed Processor on worker (handles changes asynchronously)"); changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); changeFeedProcessorInstance.start() - .subscribeOn(Schedulers.elastic()) - .doOnSuccess(aVoid -> { - //pass - }) - .subscribe(); + .subscribeOn(Schedulers.elastic()) + .doOnSuccess(aVoid -> { + //pass + }) + .subscribe(); //These two lines model an application which is inserting ten documents into the feed container - System.out.println("-->START application that inserts documents into feed container"); + logger.info("-->START application that inserts documents into feed container"); createNewDocumentsCustomPOJO(feedContainer, 10, Duration.ofSeconds(3)); isWorkCompleted = true; @@ -108,7 +107,7 @@ public static void main (String[]args) { throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); } - System.out.println("-->DELETE sample's database: " + DATABASE_NAME); + logger.info("-->DELETE sample's database: " + DATABASE_NAME); deleteDatabase(cosmosDatabase); Thread.sleep(500); @@ -117,39 +116,39 @@ public static void main (String[]args) { e.printStackTrace(); } - System.out.println("END Sample"); + logger.info("END Sample"); } public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosAsyncContainer feedContainer, CosmosAsyncContainer leaseContainer) { return ChangeFeedProcessor.changeFeedProcessorBuilder() - .setHostName(hostName) - .setFeedContainer(feedContainer) - .setLeaseContainer(leaseContainer) - .setHandleChanges((List docs) -> { - System.out.println("--->setHandleChanges() START"); - - for (JsonNode document : docs) { - try { - //Change Feed hands the document to you in the form of a JsonNode - //As a developer you have two options for handling the JsonNode document provided to you by Change Feed - //One option is to operate on the document in the form of a JsonNode, as shown below. This is great - //especially if you do not have a single uniform data model for all documents. - System.out.println("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() - .writeValueAsString(document)); - - //You can also transform the JsonNode to a POJO having the same structure as the JsonNode, - //as shown below. Then you can operate on the POJO. - CustomPOJO pojo_doc = OBJECT_MAPPER.treeToValue(document, CustomPOJO.class); - System.out.println("----=>id: " + pojo_doc.getId()); - - } catch (JsonProcessingException e) { - e.printStackTrace(); + .setHostName(hostName) + .setFeedContainer(feedContainer) + .setLeaseContainer(leaseContainer) + .setHandleChanges((List docs) -> { + logger.info("--->setHandleChanges() START"); + + for (JsonNode document : docs) { + try { + //Change Feed hands the document to you in the form of a JsonNode + //As a developer you have two options for handling the JsonNode document provided to you by Change Feed + //One option is to operate on the document in the form of a JsonNode, as shown below. This is great + //especially if you do not have a single uniform data model for all documents. + logger.info("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() + .writeValueAsString(document)); + + //You can also transform the JsonNode to a POJO having the same structure as the JsonNode, + //as shown below. Then you can operate on the POJO. + CustomPOJO pojo_doc = OBJECT_MAPPER.treeToValue(document, CustomPOJO.class); + logger.info("----=>id: " + pojo_doc.getId()); + + } catch (JsonProcessingException e) { + e.printStackTrace(); + } } - } - System.out.println("--->handleChanges() END"); + logger.info("--->handleChanges() END"); - }) - .build(); + }) + .build(); } public static CosmosAsyncClient getCosmosClient() { @@ -236,7 +235,7 @@ public static CosmosAsyncContainer createNewLeaseCollection(CosmosAsyncClient cl CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); - leaseContainerResponse = databaseLink.createContainer(containerSettings, 400,requestOptions).block(); + leaseContainerResponse = databaseLink.createContainer(containerSettings, 400, requestOptions).block(); if (leaseContainerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); @@ -252,7 +251,7 @@ public static void createNewDocumentsCustomPOJO(CosmosAsyncContainer containerCl document.setId(String.format("0%d-%s", i, suffix)); containerClient.createItem(document).subscribe(doc -> { - System.out.println("---->DOCUMENT WRITE: " + doc); + logger.info("---->DOCUMENT WRITE: " + doc); }); long remainingWork = delay.toMillis(); diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java index 86e75c7..f373f7e 100644 --- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java +++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java @@ -23,14 +23,14 @@ public final class SampleConfigurations { // The default values are credentials of the local emulator, which are not used in any production environment. // public static String MASTER_KEY = - System.getProperty("ACCOUNT_KEY", - StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("ACCOUNT_KEY")), - "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")); + System.getProperty("ACCOUNT_KEY", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("ACCOUNT_KEY")), + "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")); public static String HOST = - System.getProperty("ACCOUNT_HOST", - StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("ACCOUNT_HOST")), - "https://localhost:8081/")); + System.getProperty("ACCOUNT_HOST", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("ACCOUNT_HOST")), + "https://localhost:8081/")); } diff --git a/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java b/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java index 12bb3ba..64a7776 100644 --- a/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java +++ b/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java @@ -7,7 +7,7 @@ /** * Contains the account configurations for Sample. - * + *

* For running tests, you can pass a customized endpoint configuration in one of the following * ways: *

    @@ -15,7 +15,7 @@ * command-line option. *
  • You can set ACCOUNT_KEY and ACCOUNT_HOST as environment variables.
  • *
- * + *

* If none of the above is set, emulator endpoint will be used. * Emulator http cert is self signed. If you are using emulator, * make sure emulator https certificate is imported diff --git a/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java b/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java index 7704081..0341d1a 100644 --- a/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java +++ b/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + package com.azure.cosmos.examples.common; public class CustomPOJO { @@ -8,7 +11,7 @@ public CustomPOJO() { } public CustomPOJO(String id) { - this.id=id; + this.id = id; } public String getId() { diff --git a/src/main/java/com/azure/cosmos/examples/common/Families.java b/src/main/java/com/azure/cosmos/examples/common/Families.java index fd549ee..1f658ae 100644 --- a/src/main/java/com/azure/cosmos/examples/common/Families.java +++ b/src/main/java/com/azure/cosmos/examples/common/Families.java @@ -16,7 +16,7 @@ public static Family getAndersenFamilyItem() { Parent parent2 = new Parent(); parent2.setFirstName("Mary Kay"); - andersenFamily.setParents(new Parent[] { parent1, parent2 }); + andersenFamily.setParents(new Parent[]{parent1, parent2}); Child child1 = new Child(); child1.setFirstName("Henriette Thaulow"); @@ -26,7 +26,7 @@ public static Family getAndersenFamilyItem() { Pet pet1 = new Pet(); pet1.setGivenName("Fluffy"); - child1.setPets(new Pet[] { pet1 }); + child1.setPets(new Pet[]{pet1}); andersenFamily.setDistrict("WA5"); Address address = new Address(); @@ -53,7 +53,7 @@ public static Family getWakefieldFamilyItem() { parent2.setFamilyName("Miller"); parent2.setFirstName("Ben"); - wakefieldFamily.setParents(new Parent[] { parent1, parent2 }); + wakefieldFamily.setParents(new Parent[]{parent1, parent2}); Child child1 = new Child(); child1.setFirstName("Jesse"); @@ -66,7 +66,7 @@ public static Family getWakefieldFamilyItem() { Pet pet2 = new Pet(); pet2.setGivenName("Shadow"); - child1.setPets(new Pet[] { pet1, pet2 }); + child1.setPets(new Pet[]{pet1, pet2}); Child child2 = new Child(); child2.setFirstName("Lisa"); @@ -74,7 +74,7 @@ public static Family getWakefieldFamilyItem() { child2.setGrade(1); child2.setGender("female"); - wakefieldFamily.setChildren(new Child[] { child1, child2 }); + wakefieldFamily.setChildren(new Child[]{child1, child2}); Address address = new Address(); address.setCity("NY"); diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java index 42d604d..02c9c1e 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java @@ -58,14 +58,14 @@ public static void main(String[] args) { SampleCRUDQuickstartAsync p = new SampleCRUDQuickstartAsync(); try { - System.out.println("Starting ASYNC main"); + logger.info("Starting ASYNC main"); p.getStartedDemo(); - System.out.println("Demo complete, please hold while resources are released"); + logger.info("Demo complete, please hold while resources are released"); } catch (Exception e) { e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); + logger.error(String.format("Cosmos getStarted failed with %s", e)); } finally { - System.out.println("Closing the client"); + logger.info("Closing the client"); p.shutdown(); } } @@ -82,7 +82,7 @@ private void getStartedDemo() throws Exception { //5. Delete an item //6. Delete the Cosmos DB database and container resources and close the client. - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); // Setting the preferred location to Cosmos DB Account region @@ -92,27 +92,27 @@ private void getStartedDemo() throws Exception { // Create async client // client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildAsyncClient(); + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildAsyncClient(); // createDatabaseIfNotExists(); createContainerIfNotExists(); - Family andersenFamilyItem=Families.getAndersenFamilyItem(); - Family wakefieldFamilyItem=Families.getWakefieldFamilyItem(); - Family johnsonFamilyItem=Families.getJohnsonFamilyItem(); - Family smithFamilyItem=Families.getSmithFamilyItem(); + Family andersenFamilyItem = Families.getAndersenFamilyItem(); + Family wakefieldFamilyItem = Families.getWakefieldFamilyItem(); + Family johnsonFamilyItem = Families.getJohnsonFamilyItem(); + Family smithFamilyItem = Families.getSmithFamilyItem(); // Setup family items to create Flux familiesToCreate = Flux.just(andersenFamilyItem, - wakefieldFamilyItem, - johnsonFamilyItem, - smithFamilyItem); + wakefieldFamilyItem, + johnsonFamilyItem, + smithFamilyItem); // Creates several items in the container createFamilies(familiesToCreate); @@ -121,36 +121,36 @@ private void getStartedDemo() throws Exception { upsertFamily(wakefieldFamilyItem); familiesToCreate = Flux.just(andersenFamilyItem, - wakefieldFamilyItem, - johnsonFamilyItem, - smithFamilyItem); + wakefieldFamilyItem, + johnsonFamilyItem, + smithFamilyItem); - System.out.println("Reading items."); + logger.info("Reading items."); readItems(familiesToCreate); - System.out.println("Querying items."); + logger.info("Querying items."); queryItems(); - System.out.println("Deleting an item."); + logger.info("Deleting an item."); deleteItem(andersenFamilyItem); } private void createDatabaseIfNotExists() throws Exception { - System.out.println("Create database " + databaseName + " if not exists."); + logger.info("Create database " + databaseName + " if not exists."); // Create database if not exists // Mono databaseIfNotExists = client.createDatabaseIfNotExists(databaseName); databaseIfNotExists.flatMap(databaseResponse -> { database = databaseResponse.getDatabase(); - System.out.println("Checking database " + database.getId() + " completed!\n"); + logger.info("Checking database " + database.getId() + " completed!\n"); return Mono.empty(); }).block(); // } private void createContainerIfNotExists() throws Exception { - System.out.println("Create container " + containerName + " if not exists."); + logger.info("Create container " + containerName + " if not exists."); // Create container if not exists // @@ -161,7 +161,7 @@ private void createContainerIfNotExists() throws Exception { // Create container with 400 RU/s containerIfNotExists.flatMap(containerResponse -> { container = containerResponse.getContainer(); - System.out.println("Checking container " + container.getId() + " completed!\n"); + logger.info("Checking container " + container.getId() + " completed!\n"); return Mono.empty(); }).block(); @@ -176,42 +176,44 @@ private void createFamilies(Flux families) throws Exception { // Combine multiple item inserts, associated success println's, and a final aggregate stats println into one Reactive stream. families.flatMap(family -> { - return container.createItem(family); - }) //Flux of item request responses - .flatMap(itemResponse -> { - System.out.println(String.format("Created item with request charge of %.2f within" + - " duration %s", - itemResponse.getRequestCharge(), itemResponse.getRequestLatency())); - System.out.println(String.format("Item ID: %s\n", itemResponse.getItem().getId())); - return Mono.just(itemResponse.getRequestCharge()); - }) //Flux of request charges - .reduce(0.0, - (charge_n,charge_nplus1) -> charge_n + charge_nplus1 - ) //Mono of total charge - there will be only one item in this stream - .subscribe(charge -> { - System.out.println(String.format("Created items with total request charge of %.2f\n", - charge)); - }, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.err.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} - ); //Preserve the total charge and print aggregate charge/item count stats. + return container.createItem(family); + }) //Flux of item request responses + .flatMap(itemResponse -> { + logger.info(String.format("Created item with request charge of %.2f within" + + " duration %s", + itemResponse.getRequestCharge(), itemResponse.getRequestLatency())); + logger.info(String.format("Item ID: %s\n", itemResponse.getItem().getId())); + return Mono.just(itemResponse.getRequestCharge()); + }) //Flux of request charges + .reduce(0.0, + (charge_n, charge_nplus1) -> charge_n + charge_nplus1 + ) //Mono of total charge - there will be only one item in this stream + .subscribe(charge -> { + logger.info(String.format("Created items with total request charge of %.2f\n", + charge)); + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException) err; + cerr.printStackTrace(); + logger.error(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> { + completionLatch.countDown(); + } + ); //Preserve the total charge and print aggregate charge/item count stats. try { completionLatch.await(); } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); + throw new AssertionError("Unexpected Interruption", err); } // @@ -219,7 +221,7 @@ private void createFamilies(Flux families) throws Exception { private void upsertFamily(Family family_to_upsert) { //Modify a field of the family object - System.out.println(String.format("Upserting the item with id %s after modifying the isRegistered field...",family_to_upsert.getId())); + logger.info(String.format("Upserting the item with id %s after modifying the isRegistered field...", family_to_upsert.getId())); family_to_upsert.setRegistered(!family_to_upsert.isRegistered()); //Upsert the modified item @@ -227,7 +229,7 @@ private void upsertFamily(Family family_to_upsert) { CosmosAsyncItemResponse item_resp = container.upsertItem(family_to_upsert).block(); // Get upsert request charge and other properties like latency, and diagnostics strings, etc. - System.out.println(String.format("Upserted item with request charge of %.2f within duration %s", + logger.info(String.format("Upserted item with request charge of %.2f within duration %s", item_resp.getRequestCharge(), item_resp.getRequestLatency())); return Mono.empty(); @@ -242,36 +244,38 @@ private void readItems(Flux familiesToCreate) { final CountDownLatch completionLatch = new CountDownLatch(1); familiesToCreate.flatMap(family -> { - Mono> asyncItemResponseMono = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); - return asyncItemResponseMono; - }) - .subscribe( - itemResponse -> { - double requestCharge = itemResponse.getRequestCharge(); - Duration requestLatency = itemResponse.getRequestLatency(); - System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", + Mono> asyncItemResponseMono = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); + return asyncItemResponseMono; + }) + .subscribe( + itemResponse -> { + double requestCharge = itemResponse.getRequestCharge(); + Duration requestLatency = itemResponse.getRequestLatency(); + logger.info(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", itemResponse.getItem().getId(), requestCharge, requestLatency)); - }, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.err.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} - ); + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException) err; + cerr.printStackTrace(); + logger.error(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> { + completionLatch.countDown(); + } + ); try { completionLatch.await(); } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); + throw new AssertionError("Unexpected Interruption", err); } // @@ -288,67 +292,69 @@ private void queryItems() { queryOptions.setPopulateQueryMetrics(true); CosmosPagedFlux pagedFluxResponse = container.queryItems( - "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); + "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); final CountDownLatch completionLatch = new CountDownLatch(1); pagedFluxResponse.byPage().subscribe( - fluxResponse -> { - System.out.println("Got a page of query result with " + - fluxResponse.getResults().size() + " items(s)" - + " and request charge of " + fluxResponse.getRequestCharge()); - - System.out.println("Item Ids " + fluxResponse - .getResults() - .stream() - .map(Family::getId) - .collect(Collectors.toList())); - }, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.err.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); - } + fluxResponse -> { + logger.info("Got a page of query result with " + + fluxResponse.getResults().size() + " items(s)" + + " and request charge of " + fluxResponse.getRequestCharge()); + + logger.info("Item Ids " + fluxResponse + .getResults() + .stream() + .map(Family::getId) + .collect(Collectors.toList())); + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException) err; + cerr.printStackTrace(); + logger.error(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} + completionLatch.countDown(); + }, + () -> { + completionLatch.countDown(); + } ); try { completionLatch.await(); } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); + throw new AssertionError("Unexpected Interruption", err); } // } private void deleteItem(Family item) { - container.deleteItem(item.getId(),new PartitionKey(item.getLastName())).block(); + container.deleteItem(item.getId(), new PartitionKey(item.getLastName())).block(); } private void shutdown() { try { //Clean shutdown - System.out.println("Deleting Cosmos DB resources"); - System.out.println("-Deleting container..."); + logger.info("Deleting Cosmos DB resources"); + logger.info("-Deleting container..."); if (container != null) container.delete().subscribe(); - System.out.println("-Deleting database..."); + logger.info("-Deleting database..."); if (database != null) database.delete().subscribe(); - System.out.println("-Closing the client..."); + logger.info("-Closing the client..."); } catch (Exception err) { - System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); + logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); err.printStackTrace(); } client.close(); - System.out.println("Done."); + logger.info("Done."); } } diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java index bbcf0ec..e508f6b 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java @@ -57,12 +57,12 @@ public static void main(String[] args) { try { logger.info("Starting SYNC main"); p.getStartedDemo(); - System.out.println("Demo complete, please hold while resources are released"); + logger.info("Demo complete, please hold while resources are released"); } catch (Exception e) { e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); + logger.error(String.format("Cosmos getStarted failed with %s", e)); } finally { - System.out.println("Closing the client"); + logger.info("Closing the client"); p.shutdown(); } } @@ -79,7 +79,7 @@ private void getStartedDemo() throws Exception { //5. Delete an item //6. Delete the Cosmos DB database and container resources and close the client. - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); // Setting the preferred location to Cosmos DB Account region @@ -111,29 +111,29 @@ private void getStartedDemo() throws Exception { // Also applies an upsert operation to one of the items (create if not present, otherwise replace) createFamilies(familiesToCreate); - System.out.println("Reading items."); + logger.info("Reading items."); readItems(familiesToCreate); - System.out.println("Querying items."); + logger.info("Querying items."); queryItems(); - System.out.println("Delete an item."); + logger.info("Delete an item."); deleteItem(familiesToCreate.get(0)); } private void createDatabaseIfNotExists() throws Exception { - System.out.println("Create database " + databaseName + " if not exists."); + logger.info("Create database " + databaseName + " if not exists."); // Create database if not exists // database = client.createDatabaseIfNotExists(databaseName).getDatabase(); // - System.out.println("Checking database " + database.getId() + " completed!\n"); + logger.info("Checking database " + database.getId() + " completed!\n"); } private void createContainerIfNotExists() throws Exception { - System.out.println("Create container " + containerName + " if not exists."); + logger.info("Create container " + containerName + " if not exists."); // Create container if not exists // @@ -144,7 +144,7 @@ private void createContainerIfNotExists() throws Exception { container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); // - System.out.println("Checking container " + container.getId() + " completed!\n"); + logger.info("Checking container " + container.getId() + " completed!\n"); } private void createFamilies(List families) throws Exception { @@ -161,22 +161,22 @@ private void createFamilies(List families) throws Exception { // // Get request charge and other properties like latency, and diagnostics strings, etc. - System.out.println(String.format("Created item with request charge of %.2f within duration %s", + logger.info(String.format("Created item with request charge of %.2f within duration %s", item.getRequestCharge(), item.getRequestLatency())); totalRequestCharge += item.getRequestCharge(); } - System.out.println(String.format("Created %d items with total request charge of %.2f", + logger.info(String.format("Created %d items with total request charge of %.2f", families.size(), totalRequestCharge)); Family family_to_upsert = families.get(0); - System.out.println(String.format("Upserting the item with id %s after modifying the isRegistered field...", family_to_upsert.getId())); + logger.info(String.format("Upserting the item with id %s after modifying the isRegistered field...", family_to_upsert.getId())); family_to_upsert.setRegistered(!family_to_upsert.isRegistered()); CosmosItemResponse item = container.upsertItem(family_to_upsert); // Get upsert request charge and other properties like latency, and diagnostics strings, etc. - System.out.println(String.format("Upserted item with request charge of %.2f within duration %s", + logger.info(String.format("Upserted item with request charge of %.2f within duration %s", item.getRequestCharge(), item.getRequestLatency())); } @@ -189,11 +189,11 @@ private void readItems(ArrayList familiesToCreate) { CosmosItemResponse item = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); double requestCharge = item.getRequestCharge(); Duration requestLatency = item.getRequestLatency(); - System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", + logger.info(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", item.getResource().getId(), requestCharge, requestLatency)); } catch (CosmosClientException e) { e.printStackTrace(); - System.out.println(String.format("Read Item failed with %s", e)); + logger.info(String.format("Read Item failed with %s", e)); } // }); @@ -212,11 +212,11 @@ private void queryItems() { "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); familiesPagedIterable.iterableByPage().forEach(cosmosItemPropertiesFeedResponse -> { - System.out.println("Got a page of query result with " + + logger.info("Got a page of query result with " + cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)" + " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()); - System.out.println("Item Ids " + cosmosItemPropertiesFeedResponse + logger.info("Item Ids " + cosmosItemPropertiesFeedResponse .getResults() .stream() .map(Family::getId) @@ -232,19 +232,19 @@ private void deleteItem(Family item) { private void shutdown() { try { //Clean shutdown - System.out.println("Deleting Cosmos DB resources"); - System.out.println("-Deleting container..."); + logger.info("Deleting Cosmos DB resources"); + logger.info("-Deleting container..."); if (container != null) container.delete(); - System.out.println("-Deleting database..."); + logger.info("-Deleting database..."); if (database != null) database.delete(); - System.out.println("-Closing the client..."); + logger.info("-Closing the client..."); } catch (Exception err) { - System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); + logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); err.printStackTrace(); } client.close(); - System.out.println("Done."); + logger.info("Done."); } } diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java index 2419daf..4197819 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java @@ -63,14 +63,14 @@ public static void main(String[] args) { SampleIndexManagementAsync p = new SampleIndexManagementAsync(); try { - System.out.println("Starting ASYNC main"); + logger.info("Starting ASYNC main"); p.indexManagementDemo(); - System.out.println("Demo complete, please hold while resources are released"); + logger.info("Demo complete, please hold while resources are released"); } catch (Exception e) { e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); + logger.error(String.format("Cosmos getStarted failed with %s", e)); } finally { - System.out.println("Closing the client"); + logger.info("Closing the client"); p.shutdown(); } } @@ -82,7 +82,7 @@ private void indexManagementDemo() throws Exception { //Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of //indexing capabilities. - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); // Setting the preferred location to Cosmos DB Account region @@ -105,10 +105,10 @@ private void indexManagementDemo() throws Exception { //Here is where index management is performed createContainerIfNotExistsWithSpecifiedIndex(); - Family andersenFamilyItem=Families.getAndersenFamilyItem(); - Family wakefieldFamilyItem=Families.getWakefieldFamilyItem(); - Family johnsonFamilyItem=Families.getJohnsonFamilyItem(); - Family smithFamilyItem=Families.getSmithFamilyItem(); + Family andersenFamilyItem = Families.getAndersenFamilyItem(); + Family wakefieldFamilyItem = Families.getWakefieldFamilyItem(); + Family johnsonFamilyItem = Families.getJohnsonFamilyItem(); + Family smithFamilyItem = Families.getSmithFamilyItem(); // Setup family items to create Flux familiesToCreate = Flux.just(andersenFamilyItem, @@ -123,29 +123,29 @@ private void indexManagementDemo() throws Exception { johnsonFamilyItem, smithFamilyItem); - System.out.println("Reading items."); + logger.info("Reading items."); readItems(familiesToCreate); - System.out.println("Querying items."); + logger.info("Querying items."); queryItems(); } private void createDatabaseIfNotExists() throws Exception { - System.out.println("Create database " + databaseName + " if not exists."); + logger.info("Create database " + databaseName + " if not exists."); // Create database if not exists // Mono databaseIfNotExists = client.createDatabaseIfNotExists(databaseName); databaseIfNotExists.flatMap(databaseResponse -> { database = databaseResponse.getDatabase(); - System.out.println("Checking database " + database.getId() + " completed!\n"); + logger.info("Checking database " + database.getId() + " completed!\n"); return Mono.empty(); }).block(); // } private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception { - System.out.println("Create container " + containerName + " if not exists."); + logger.info("Create container " + containerName + " if not exists."); // Create container if not exists // @@ -213,7 +213,7 @@ private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception { // Create container with 400 RU/s containerIfNotExists.flatMap(containerResponse -> { container = containerResponse.getContainer(); - System.out.println("Checking container " + container.getId() + " completed!\n"); + logger.info("Checking container " + container.getId() + " completed!\n"); return Mono.empty(); }).block(); @@ -231,25 +231,25 @@ private void createFamilies(Flux families) throws Exception { return container.createItem(family); }) //Flux of item request responses .flatMap(itemResponse -> { - System.out.println(String.format("Created item with request charge of %.2f within" + + logger.info(String.format("Created item with request charge of %.2f within" + " duration %s", itemResponse.getRequestCharge(), itemResponse.getRequestLatency())); - System.out.println(String.format("Item ID: %s\n", itemResponse.getItem().getId())); + logger.info(String.format("Item ID: %s\n", itemResponse.getItem().getId())); return Mono.just(itemResponse.getRequestCharge()); }) //Flux of request charges .reduce(0.0, - (charge_n,charge_nplus1) -> charge_n + charge_nplus1 + (charge_n, charge_nplus1) -> charge_n + charge_nplus1 ) //Mono of total charge - there will be only one item in this stream .subscribe(charge -> { - System.out.println(String.format("Created items with total request charge of %.2f\n", + logger.info(String.format("Created items with total request charge of %.2f\n", charge)); }, err -> { if (err instanceof CosmosClientException) { //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; + CosmosClientException cerr = (CosmosClientException) err; cerr.printStackTrace(); - System.out.println(String.format("Read Item failed with %s\n", cerr)); + logger.info(String.format("Read Item failed with %s\n", cerr)); } else { //General errors err.printStackTrace(); @@ -257,13 +257,15 @@ private void createFamilies(Flux families) throws Exception { completionLatch.countDown(); }, - () -> {completionLatch.countDown();} + () -> { + completionLatch.countDown(); + } ); //Preserve the total charge and print aggregate charge/item count stats. try { completionLatch.await(); } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); + throw new AssertionError("Unexpected Interruption", err); } // @@ -284,15 +286,15 @@ private void readItems(Flux familiesToCreate) { itemResponse -> { double requestCharge = itemResponse.getRequestCharge(); Duration requestLatency = itemResponse.getRequestLatency(); - System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", + logger.info(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", itemResponse.getItem().getId(), requestCharge, requestLatency)); }, err -> { if (err instanceof CosmosClientException) { //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; + CosmosClientException cerr = (CosmosClientException) err; cerr.printStackTrace(); - System.out.println(String.format("Read Item failed with %s\n", cerr)); + logger.info(String.format("Read Item failed with %s\n", cerr)); } else { //General errors err.printStackTrace(); @@ -300,13 +302,15 @@ private void readItems(Flux familiesToCreate) { completionLatch.countDown(); }, - () -> {completionLatch.countDown();} + () -> { + completionLatch.countDown(); + } ); try { completionLatch.await(); } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); + throw new AssertionError("Unexpected Interruption", err); } // @@ -328,11 +332,11 @@ private void queryItems() { pagedFluxResponse.byPage().subscribe( fluxResponse -> { - System.out.println("Got a page of query result with " + + logger.info("Got a page of query result with " + fluxResponse.getResults().size() + " items(s)" + " and request charge of " + fluxResponse.getRequestCharge()); - System.out.println("Item Ids " + fluxResponse + logger.info("Item Ids " + fluxResponse .getResults() .stream() .map(Family::getId) @@ -341,9 +345,9 @@ private void queryItems() { err -> { if (err instanceof CosmosClientException) { //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; + CosmosClientException cerr = (CosmosClientException) err; cerr.printStackTrace(); - System.err.println(String.format("Read Item failed with %s\n", cerr)); + logger.error(String.format("Read Item failed with %s\n", cerr)); } else { //General errors err.printStackTrace(); @@ -351,13 +355,15 @@ private void queryItems() { completionLatch.countDown(); }, - () -> {completionLatch.countDown();} + () -> { + completionLatch.countDown(); + } ); try { completionLatch.await(); } catch (InterruptedException err) { - throw new AssertionError("Unexpected Interruption",err); + throw new AssertionError("Unexpected Interruption", err); } // @@ -366,19 +372,19 @@ private void queryItems() { private void shutdown() { try { //Clean shutdown - System.out.println("Deleting Cosmos DB resources"); - System.out.println("-Deleting container..."); + logger.info("Deleting Cosmos DB resources"); + logger.info("-Deleting container..."); if (container != null) container.delete().subscribe(); - System.out.println("-Deleting database..."); + logger.info("-Deleting database..."); if (database != null) database.delete().subscribe(); - System.out.println("-Closing the client..."); + logger.info("-Closing the client..."); } catch (Exception err) { - System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); + logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); err.printStackTrace(); } client.close(); - System.out.println("Done."); + logger.info("Done."); } } diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java index 2ed1f4d..4fb1965 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java @@ -60,14 +60,14 @@ public static void main(String[] args) { SampleIndexManagement p = new SampleIndexManagement(); try { - System.out.println("Starting SYNC main"); + logger.info("Starting SYNC main"); p.indexManagementDemo(); - System.out.println("Demo complete, please hold while resources are released"); + logger.info("Demo complete, please hold while resources are released"); } catch (Exception e) { e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); + logger.error(String.format("Cosmos getStarted failed with %s", e)); } finally { - System.out.println("Closing the client"); + logger.info("Closing the client"); p.shutdown(); } } @@ -79,7 +79,7 @@ private void indexManagementDemo() throws Exception { //Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of //indexing capabilities. - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); // Setting the preferred location to Cosmos DB Account region @@ -111,26 +111,26 @@ private void indexManagementDemo() throws Exception { createFamilies(familiesToCreate); - System.out.println("Reading items."); + logger.info("Reading items."); readItems(familiesToCreate); - System.out.println("Querying items."); + logger.info("Querying items."); queryItems(); } private void createDatabaseIfNotExists() throws Exception { - System.out.println("Create database " + databaseName + " if not exists."); + logger.info("Create database " + databaseName + " if not exists."); // Create database if not exists // database = client.createDatabaseIfNotExists(databaseName).getDatabase(); // - System.out.println("Checking database " + database.getId() + " completed!\n"); + logger.info("Checking database " + database.getId() + " completed!\n"); } private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception { - System.out.println("Create container " + containerName + " if not exists."); + logger.info("Create container " + containerName + " if not exists."); // Create container if not exists CosmosContainerProperties containerProperties = @@ -195,7 +195,7 @@ private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception { // Create container with 400 RU/s container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); - System.out.println("Checking container " + container.getId() + " completed!\n"); + logger.info("Checking container " + container.getId() + " completed!\n"); } private void createFamilies(List families) throws Exception { @@ -212,12 +212,12 @@ private void createFamilies(List families) throws Exception { // // Get request charge and other properties like latency, and diagnostics strings, etc. - System.out.println(String.format("Created item with request charge of %.2f within" + + logger.info(String.format("Created item with request charge of %.2f within" + " duration %s", item.getRequestCharge(), item.getRequestLatency())); totalRequestCharge += item.getRequestCharge(); } - System.out.println(String.format("Created %d items with total request " + + logger.info(String.format("Created %d items with total request " + "charge of %.2f", families.size(), totalRequestCharge)); @@ -232,11 +232,11 @@ private void readItems(ArrayList familiesToCreate) { CosmosItemResponse item = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class); double requestCharge = item.getRequestCharge(); Duration requestLatency = item.getRequestLatency(); - System.out.println(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", + logger.info(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", item.getResource().getId(), requestCharge, requestLatency)); } catch (CosmosClientException e) { e.printStackTrace(); - System.err.println(String.format("Read Item failed with %s", e)); + logger.error(String.format("Read Item failed with %s", e)); } // }); @@ -254,11 +254,11 @@ private void queryItems() { "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); familiesPagedIterable.iterableByPage().forEach(cosmosItemPropertiesFeedResponse -> { - System.out.println("Got a page of query result with " + + logger.info("Got a page of query result with " + cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)" + " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()); - System.out.println("Item Ids " + cosmosItemPropertiesFeedResponse + logger.info("Item Ids " + cosmosItemPropertiesFeedResponse .getResults() .stream() .map(Family::getId) @@ -270,19 +270,19 @@ private void queryItems() { private void shutdown() { try { //Clean shutdown - System.out.println("Deleting Cosmos DB resources"); - System.out.println("-Deleting container..."); + logger.info("Deleting Cosmos DB resources"); + logger.info("-Deleting container..."); if (container != null) container.delete(); - System.out.println("-Deleting database..."); + logger.info("-Deleting database..."); if (database != null) database.delete(); - System.out.println("-Closing the client..."); + logger.info("-Closing the client..."); } catch (Exception err) { - System.err.println("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); + logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below."); err.printStackTrace(); } client.close(); - System.out.println("Done."); + logger.info("Done."); } } diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java index f0953da..8c8cf33 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. @@ -61,12 +60,12 @@ public static void main(String[] args) { try { p.sprocDemo(); - System.out.println("Demo complete, please hold while resources are released"); + logger.info("Demo complete, please hold while resources are released"); p.shutdown(); - System.out.println("Done.\n"); + logger.info("Done.\n"); } catch (Exception e) { e.printStackTrace(); - System.out.println(String.format("Cosmos getStarted failed with %s", e)); + logger.info(String.format("Cosmos getStarted failed with %s", e)); p.close(); } finally { } @@ -87,15 +86,15 @@ private void sprocDemo() throws Exception { executeStoredProcedure(); //Perform a point-read to confirm that the item with id test_doc exists - System.out.println("Checking that a document was created by the stored procedure..."); + logger.info("Checking that a document was created by the stored procedure..."); CosmosAsyncItemResponse test_resp = - container.readItem("test_doc",new PartitionKey("test_doc"),CustomPOJO.class).block(); - System.out.println(String.format( - "Status return value of point-read for document created by stored procedure (200 indicates success): %d",test_resp.getStatusCode())); + container.readItem("test_doc", new PartitionKey("test_doc"), CustomPOJO.class).block(); + logger.info(String.format( + "Status return value of point-read for document created by stored procedure (200 indicates success): %d", test_resp.getStatusCode())); } - public void setUp() throws Exception{ - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + public void setUp() throws Exception { + logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); // Setting the preferred location to Cosmos DB Account region @@ -105,25 +104,25 @@ public void setUp() throws Exception{ // Create sync client // client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildAsyncClient(); + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildAsyncClient(); - System.out.println("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n"); + logger.info("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n"); - client.createDatabaseIfNotExists(databaseName).flatMap(databaseResponse -> { - database = databaseResponse.getDatabase(); - return Mono.empty(); - }).block(); + client.createDatabaseIfNotExists(databaseName).flatMap(databaseResponse -> { + database = databaseResponse.getDatabase(); + return Mono.empty(); + }).block(); - CosmosContainerProperties containerProperties = + CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/id"); - database.createContainerIfNotExists(containerProperties, 400).flatMap(containerResponse -> { - container = containerResponse.getContainer(); - return Mono.empty(); - }).block(); + database.createContainerIfNotExists(containerProperties, 400).flatMap(containerResponse -> { + container = containerResponse.getContainer(); + return Mono.empty(); + }).block(); } public void shutdown() throws Exception { @@ -132,24 +131,24 @@ public void shutdown() throws Exception { } public void createStoredProcedure() throws Exception { - System.out.println("Creating stored procedure...\n"); + logger.info("Creating stored procedure...\n"); sprocId = "createMyDocument"; String sprocBody = "function createMyDocument() {\n" + - "var documentToCreate = {\"id\":\"test_doc\"}\n" + - "var context = getContext();\n" + - "var collection = context.getCollection();\n" + - "var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" + - " function (err, documentCreated) {\n" + - "if (err) throw new Error('Error' + err.message);\n" + - "context.getResponse().setBody(documentCreated.id)\n" + - "});\n" + - "if (!accepted) return;\n" + - "}"; - CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId,sprocBody); + "var documentToCreate = {\"id\":\"test_doc\"}\n" + + "var context = getContext();\n" + + "var collection = context.getCollection();\n" + + "var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" + + " function (err, documentCreated) {\n" + + "if (err) throw new Error('Error' + err.message);\n" + + "context.getResponse().setBody(documentCreated.id)\n" + + "});\n" + + "if (!accepted) return;\n" + + "}"; + CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId, sprocBody); container.getScripts() - .createStoredProcedure(storedProcedureDef, - new CosmosStoredProcedureRequestOptions()).block(); + .createStoredProcedure(storedProcedureDef, + new CosmosStoredProcedureRequestOptions()).block(); } private void readAllSprocs() throws Exception { @@ -161,58 +160,60 @@ private void readAllSprocs() throws Exception { final CountDownLatch completionLatch = new CountDownLatch(1); - fluxResponse.flatMap(storedProcedureProperties -> { - System.out.println(String.format("Stored Procedure: %s\n",storedProcedureProperties.getId())); + logger.info(String.format("Stored Procedure: %s\n", storedProcedureProperties.getId())); return Mono.empty(); }).subscribe( - s -> {}, - err -> { - if (err instanceof CosmosClientException) { - //Client-specific errors - CosmosClientException cerr = (CosmosClientException)err; - cerr.printStackTrace(); - System.out.println(String.format("Read Item failed with %s\n", cerr)); - } else { - //General errors - err.printStackTrace(); + s -> { + }, + err -> { + if (err instanceof CosmosClientException) { + //Client-specific errors + CosmosClientException cerr = (CosmosClientException) err; + cerr.printStackTrace(); + logger.info(String.format("Read Item failed with %s\n", cerr)); + } else { + //General errors + err.printStackTrace(); + } + + completionLatch.countDown(); + }, + () -> { + completionLatch.countDown(); } - - completionLatch.countDown(); - }, - () -> {completionLatch.countDown();} ); completionLatch.await(); } public void executeStoredProcedure() throws Exception { - System.out.println(String.format("Executing stored procedure %s...\n\n",sprocId)); + logger.info(String.format("Executing stored procedure %s...\n\n", sprocId)); CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions(); options.setPartitionKey(new PartitionKey("test_doc")); container.getScripts() - .getStoredProcedure(sprocId) - .execute(null, options) - .flatMap(executeResponse -> { - System.out.println(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", - sprocId, - executeResponse.getResponseAsString(), - executeResponse.getStatusCode(), - executeResponse.getRequestCharge())); - return Mono.empty(); - }).block(); + .getStoredProcedure(sprocId) + .execute(null, options) + .flatMap(executeResponse -> { + logger.info(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", + sprocId, + executeResponse.getResponseAsString(), + executeResponse.getStatusCode(), + executeResponse.getRequestCharge())); + return Mono.empty(); + }).block(); } public void deleteStoredProcedure() throws Exception { - System.out.println("-Deleting stored procedure...\n"); + logger.info("-Deleting stored procedure...\n"); container.getScripts() - .getStoredProcedure(sprocId) - .delete().block(); - System.out.println("-Deleting database...\n"); + .getStoredProcedure(sprocId) + .delete().block(); + logger.info("-Deleting database...\n"); database.delete().block(); - System.out.println("-Closing client instance...\n"); + logger.info("-Closing client instance...\n"); client.close(); } } diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java index b4d0e4b..5716608 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java @@ -55,12 +55,12 @@ public static void main(String[] args) { try { p.sprocDemo(); - System.out.println("Demo complete, please hold while resources are released"); + logger.info("Demo complete, please hold while resources are released"); p.shutdown(); - System.out.println("Done.\n"); + logger.info("Done.\n"); } catch (Exception e) { e.printStackTrace(); - System.err.println(String.format("Cosmos getStarted failed with %s", e)); + logger.error(String.format("Cosmos getStarted failed with %s", e)); p.close(); } finally { } @@ -69,26 +69,26 @@ public static void main(String[] args) { // private void sprocDemo() throws Exception { - //Setup client, DB, and the container for which we will create stored procedures - //The container partition key will be id - setUp(); - - //Create stored procedure and list all stored procedures that have been created. - createStoredProcedure(); - readAllSprocs(); - - //Execute the stored procedure, which we expect will create an item with id test_doc - executeStoredProcedure(); - - //Perform a point-read to confirm that the item with id test_doc exists - System.out.println("Checking that a document was created by the stored procedure..."); - CosmosItemResponse test_resp = container.readItem("test_doc",new PartitionKey("test_doc"),CustomPOJO.class); - System.out.println(String.format( - "Result of point-read for document created by stored procedure (200 indicates success): %d",test_resp.getStatusCode())); + //Setup client, DB, and the container for which we will create stored procedures + //The container partition key will be id + setUp(); + + //Create stored procedure and list all stored procedures that have been created. + createStoredProcedure(); + readAllSprocs(); + + //Execute the stored procedure, which we expect will create an item with id test_doc + executeStoredProcedure(); + + //Perform a point-read to confirm that the item with id test_doc exists + logger.info("Checking that a document was created by the stored procedure..."); + CosmosItemResponse test_resp = container.readItem("test_doc", new PartitionKey("test_doc"), CustomPOJO.class); + logger.info(String.format( + "Result of point-read for document created by stored procedure (200 indicates success): %d", test_resp.getStatusCode())); } - public void setUp() throws Exception{ - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); + public void setUp() throws Exception { + logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy(); // Setting the preferred location to Cosmos DB Account region @@ -98,19 +98,19 @@ public void setUp() throws Exception{ // Create sync client // client = new CosmosClientBuilder() - .setEndpoint(AccountSettings.HOST) - .setKey(AccountSettings.MASTER_KEY) - .setConnectionPolicy(defaultPolicy) - .setConsistencyLevel(ConsistencyLevel.EVENTUAL) - .buildClient(); + .setEndpoint(AccountSettings.HOST) + .setKey(AccountSettings.MASTER_KEY) + .setConnectionPolicy(defaultPolicy) + .setConsistencyLevel(ConsistencyLevel.EVENTUAL) + .buildClient(); - System.out.println("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n"); + logger.info("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n"); - database = client.createDatabaseIfNotExists(databaseName).getDatabase(); + database = client.createDatabaseIfNotExists(databaseName).getDatabase(); - CosmosContainerProperties containerProperties = + CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/id"); - container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); + container = database.createContainerIfNotExists(containerProperties, 400).getContainer(); } public void shutdown() throws Exception { @@ -119,28 +119,28 @@ public void shutdown() throws Exception { } public void createStoredProcedure() throws Exception { - System.out.println("Creating stored procedure..."); + logger.info("Creating stored procedure..."); sprocId = "createMyDocument"; String sprocBody = "function createMyDocument() {\n" + - "var documentToCreate = {\"id\":\"test_doc\"}\n" + - "var context = getContext();\n" + - "var collection = context.getCollection();\n" + - "var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" + - " function (err, documentCreated) {\n" + - "if (err) throw new Error('Error' + err.message);\n" + - "context.getResponse().setBody(documentCreated.id)\n" + - "});\n" + - "if (!accepted) return;\n" + - "}"; - CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId,sprocBody); + "var documentToCreate = {\"id\":\"test_doc\"}\n" + + "var context = getContext();\n" + + "var collection = context.getCollection();\n" + + "var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" + + " function (err, documentCreated) {\n" + + "if (err) throw new Error('Error' + err.message);\n" + + "context.getResponse().setBody(documentCreated.id)\n" + + "});\n" + + "if (!accepted) return;\n" + + "}"; + CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId, sprocBody); container.getScripts() - .createStoredProcedure(storedProcedureDef, - new CosmosStoredProcedureRequestOptions()); + .createStoredProcedure(storedProcedureDef, + new CosmosStoredProcedureRequestOptions()); } private void readAllSprocs() throws Exception { - System.out.println("Listing all stored procedures associated with container " + containerName + "\n"); + logger.info("Listing all stored procedures associated with container " + containerName + "\n"); FeedOptions feedOptions = new FeedOptions(); CosmosPagedIterable feedResponseIterable = @@ -148,37 +148,37 @@ private void readAllSprocs() throws Exception { Iterator feedResponseIterator = feedResponseIterable.iterator(); - while(feedResponseIterator.hasNext()) { + while (feedResponseIterator.hasNext()) { CosmosStoredProcedureProperties storedProcedureProperties = feedResponseIterator.next(); - System.out.println(String.format("Stored Procedure: %s",storedProcedureProperties)); + logger.info(String.format("Stored Procedure: %s", storedProcedureProperties)); } } public void executeStoredProcedure() throws Exception { - System.out.println(String.format("Executing stored procedure %s...\n\n",sprocId)); + logger.info(String.format("Executing stored procedure %s...\n\n", sprocId)); CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions(); options.setPartitionKey(new PartitionKey("test_doc")); CosmosStoredProcedureResponse executeResponse = container.getScripts() - .getStoredProcedure(sprocId) - .execute(null, options); - - System.out.println(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", - sprocId, - executeResponse.responseAsString(), - executeResponse.getStatusCode(), - executeResponse.getRequestCharge())); + .getStoredProcedure(sprocId) + .execute(null, options); + + logger.info(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", + sprocId, + executeResponse.responseAsString(), + executeResponse.getStatusCode(), + executeResponse.getRequestCharge())); } public void deleteStoredProcedure() throws Exception { - System.out.println("-Deleting stored procedure...\n"); + logger.info("-Deleting stored procedure...\n"); container.getScripts() - .getStoredProcedure(sprocId) - .delete(); - System.out.println("-Deleting database...\n"); + .getStoredProcedure(sprocId) + .delete(); + logger.info("-Deleting database...\n"); database.delete(); - System.out.println("-Closing client instance...\n"); + logger.info("-Closing client instance...\n"); client.close(); - System.out.println("Done."); + logger.info("Done."); } } diff --git a/src/main/resources/log4j2.properties b/src/main/resources/log4j2.properties index fccb3cc..f1178ab 100644 --- a/src/main/resources/log4j2.properties +++ b/src/main/resources/log4j2.properties @@ -1,18 +1,14 @@ # this is the log4j configuration for tests - # Set root logger level to WARN and its appender to STDOUT. -rootLogger.level = INFO -rootLogger.appenderRef.stdout.ref = STDOUT - -logger.netty.name = io.netty -logger.netty.level = INFO - -logger.cosmos.name = com.azure.cosmos -logger.cosmos.level = INFO - +rootLogger.level=INFO +rootLogger.appenderRef.stdout.ref=STDOUT +logger.netty.name=io.netty +logger.netty.level=INFO +logger.cosmos.name=com.azure.cosmos +logger.cosmos.level=INFO # STDOUT is a ConsoleAppender and uses PatternLayout. -appender.console.name = STDOUT -appender.console.type = Console -appender.console.layout.type = PatternLayout -appender.console.layout.pattern = %m%n +appender.console.name=STDOUT +appender.console.type=Console +appender.console.layout.type=PatternLayout +appender.console.layout.pattern=%m%n From 18f564b0a1a05f653e4b8fecef90a0a7ab8a31af Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Tue, 10 Mar 2020 13:54:53 -0700 Subject: [PATCH 10/11] Manual merge of changes from master: make README.md IDE-agnostic; improve explanatory comments in all samples --- README.md | 9 +++------ .../changefeed/SampleChangeFeedProcessor.java | 14 +++++++------- .../async/SampleCRUDQuickstartAsync.java | 17 ++++++++--------- .../sync/SampleCRUDQuickstart.java | 17 ++++++++--------- .../async/SampleIndexManagementAsync.java | 7 +++---- .../sync/SampleIndexManagement.java | 7 +++---- .../async/SampleStoredProcedureAsync.java | 8 ++++++-- .../sync/SampleStoredProcedure.java | 8 ++++++-- 8 files changed, 44 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 4162be7..4ad3657 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,6 @@ Sample code repo for Azure Cosmos DB Java SDK for SQL API. By cloning and runnin ## Prerequisites -* A Java IDE such as IntelliJ IDEA or VSCode * Maven * Java SE JRE 8 * Setting up an Azure Cosmos DB account through the Azure Portal. The **Create a database account** section of [this guide](https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-java) walks you through account creation. @@ -46,17 +45,15 @@ Clone the sample to your PC. Using your Java IDE, open pom.xml as a Maven projec ## Running the sample -*If you are using Intellij IDEA as your Java IDE:* Once you have opened the project, go to the **Run/Debug Configurations** drop-down and choose **Edit Configurations**. -In the **Edit Configurations** dialog, click the **+** (**Add New Configuration**) button, select **Application** as the configuration type, - and give the new configuration a name. Once you are looking at the settings for your new Configuration, find **Environment variables** and paste +These environment variables must be set ``` ACCOUNT_HOST=your account hostname;ACCOUNT_KEY=your account master key ``` -which gives the sample read/write access to your account. +in order to give the samples read/write access to your account. -To choose which sample will run, populate the **Main class** field of the Configuration with +To run a sample, specify its Main Class ``` com.azure.cosmos.examples.sample.synchronicity.MainClass diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java index 5a28566..48000b6 100644 --- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java +++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java @@ -28,7 +28,13 @@ /** * Sample for Change Feed Processor. - */ + * This sample models an application where documents are being inserted into one container (the "feed container"), + * and meanwhile another worker thread or worker application is pulling inserted documents from the feed container's Change Feed + * and operating on them in some way. For one or more workers to process the Change Feed of a container, the workers must first contact the server + * and "lease" access to monitor one or more partitions of the feed container. The Change Feed Processor Library + * handles leasing automatically for you, however you must create a separate "lease container" where the Change Feed + * Processor Library can store and track leases container partitions. +*/ public class SampleChangeFeedProcessor { public static int WAIT_FOR_WORK = 60000; @@ -45,12 +51,6 @@ public static void main(String[] args) { logger.info("BEGIN Sample"); try { - //This sample models an application where documents are being inserted into one container (the "feed container"), - //and meanwhile another worker thread or worker application is pulling inserted documents from the feed container's Change Feed - //and operating on them in some way. For one or more workers to process the Change Feed of a container, the workers must first contact the server - //and "lease" access to monitor one or more partitions of the feed container. The Change Feed Processor Library - //handles leasing automatically for you, however you must create a separate "lease container" where the Change Feed - //Processor Library can store and track leases container partitions. //Summary of the next four commands: //-Create an asynchronous Azure Cosmos DB client and database so that we can issue async requests to the DB diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java index 02c9c1e..5e67558 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java @@ -51,7 +51,14 @@ public void close() { /** * Run a Hello CosmosDB console application. * - * @param args command line args. + * This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations + * with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will + * 1. Create asynchronous client, database and container instances + * 2. Create several items + * 3. Upsert one of the items + * 4. Perform a query over the items + * 5. Delete an item + * 6. Delete the Cosmos DB database and container resources and close the client. */ //

public static void main(String[] args) { @@ -73,14 +80,6 @@ public static void main(String[] args) { //
private void getStartedDemo() throws Exception { - //This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations - //with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will - //1. Create asynchronous client, database and container instances - //2. Create several items - //3. Upsert one of the items - //4. Perform a query over the items - //5. Delete an item - //6. Delete the Cosmos DB database and container resources and close the client. logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java index e508f6b..cd029ec 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java @@ -48,7 +48,14 @@ public void close() { /** * Run a Hello CosmosDB console application. * - * @param args command line args. + * This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations + * with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will + * 1. Create synchronous client, database and container instances + * 2. Create several items + * 3. Upsert one of the items + * 4. Perform a query over the items + * 5. Delete an item + * 6. Delete the Cosmos DB database and container resources and close the client. * */ //
public static void main(String[] args) { @@ -70,14 +77,6 @@ public static void main(String[] args) { //
private void getStartedDemo() throws Exception { - //This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations - //with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will - //1. Create synchronous client, database and container instances - //2. Create several items - //3. Upsert one of the items - //4. Perform a query over the items - //5. Delete an item - //6. Delete the Cosmos DB database and container resources and close the client. logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java index 4197819..9eeac8c 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java @@ -56,7 +56,9 @@ public void close() { /** * Run a Hello CosmosDB console application. * - * @param args command line args. + * This sample is similar to SampleCRUDQuickstartAsync, but modified to show indexing capabilities of Cosmos DB. + * Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of + * indexing capabilities. */ //
public static void main(String[] args) { @@ -78,9 +80,6 @@ public static void main(String[] args) { //
private void indexManagementDemo() throws Exception { - //This sample is similar to SampleCRUDQuickstartAsync, but modified to show indexing capabilities of Cosmos DB. - //Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of - //indexing capabilities. logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java index 4fb1965..ef15823 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java @@ -52,7 +52,9 @@ public void close() { /** * Run a Hello CosmosDB console application. * - * @param args command line args. + * This sample is similar to SampleCRUDQuickstart, but modified to show indexing capabilities of Cosmos DB. + * Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of + * indexing capabilities. */ //
public static void main(String[] args) { @@ -75,9 +77,6 @@ public static void main(String[] args) { //
private void indexManagementDemo() throws Exception { - //This sample is similar to SampleCRUDQuickstart, but modified to show indexing capabilities of Cosmos DB. - //Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of - //indexing capabilities. logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java index 8c8cf33..4aa2427 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java @@ -50,9 +50,13 @@ public void close() { } /** - * Run a Hello CosmosDB console application. + * Stored Procedure Example + * + * This sample code demonstrates creation, execution, and effects of stored procedures + * using Java SDK. A stored procedure is created which will insert a JSON object into + * a Cosmos DB container. The sample executes the stored procedure and then performs + * a point-read to confirm that the stored procedure had the intended effect. * - * @param args command line args. */ //
public static void main(String[] args) { diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java index 5716608..55331f2 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java @@ -45,9 +45,13 @@ public void close() { } /** - * Run a Hello CosmosDB console application. + * Stored Procedure Example + * + * This sample code demonstrates creation, execution, and effects of stored procedures + * using Java SDK. A stored procedure is created which will insert a JSON object into + * a Cosmos DB container. The sample executes the stored procedure and then performs + * a point-read to confirm that the stored procedure had the intended effect. * - * @param args command line args. */ //
public static void main(String[] args) { From ad653553911fcc3a6ce023575b2b952f94f4209d Mon Sep 17 00:00:00 2001 From: Andrew Feldman Date: Tue, 10 Mar 2020 13:58:05 -0700 Subject: [PATCH 11/11] Cleaned up the code --- .../cosmos/examples/changefeed/SampleChangeFeedProcessor.java | 2 +- .../crudquickstart/async/SampleCRUDQuickstartAsync.java | 2 +- .../examples/crudquickstart/sync/SampleCRUDQuickstart.java | 2 +- .../indexmanagement/async/SampleIndexManagementAsync.java | 2 +- .../examples/indexmanagement/sync/SampleIndexManagement.java | 2 +- .../storedprocedure/async/SampleStoredProcedureAsync.java | 3 +-- .../examples/storedprocedure/sync/SampleStoredProcedure.java | 3 +-- 7 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java index 48000b6..5c07fea 100644 --- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java +++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java @@ -34,7 +34,7 @@ * and "lease" access to monitor one or more partitions of the feed container. The Change Feed Processor Library * handles leasing automatically for you, however you must create a separate "lease container" where the Change Feed * Processor Library can store and track leases container partitions. -*/ + */ public class SampleChangeFeedProcessor { public static int WAIT_FOR_WORK = 60000; diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java index 5e67558..379ee18 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java @@ -50,7 +50,7 @@ public void close() { /** * Run a Hello CosmosDB console application. - * + *

* This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations * with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will * 1. Create asynchronous client, database and container instances diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java index cd029ec..0659d25 100644 --- a/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java +++ b/src/main/java/com/azure/cosmos/examples/crudquickstart/sync/SampleCRUDQuickstart.java @@ -47,7 +47,7 @@ public void close() { /** * Run a Hello CosmosDB console application. - * + *

* This is a simple sample application intended to demonstrate Create, Read, Update, Delete (CRUD) operations * with Azure Cosmos DB Java SDK, as applied to databases, containers and items. This sample will * 1. Create synchronous client, database and container instances diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java index 9eeac8c..34628ff 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java @@ -55,7 +55,7 @@ public void close() { /** * Run a Hello CosmosDB console application. - * + *

* This sample is similar to SampleCRUDQuickstartAsync, but modified to show indexing capabilities of Cosmos DB. * Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of * indexing capabilities. diff --git a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java index ef15823..748dbfe 100644 --- a/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java +++ b/src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java @@ -51,7 +51,7 @@ public void close() { /** * Run a Hello CosmosDB console application. - * + *

* This sample is similar to SampleCRUDQuickstart, but modified to show indexing capabilities of Cosmos DB. * Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of * indexing capabilities. diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java index 4aa2427..21ca683 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java @@ -51,12 +51,11 @@ public void close() { /** * Stored Procedure Example - * + *

* This sample code demonstrates creation, execution, and effects of stored procedures * using Java SDK. A stored procedure is created which will insert a JSON object into * a Cosmos DB container. The sample executes the stored procedure and then performs * a point-read to confirm that the stored procedure had the intended effect. - * */ //

public static void main(String[] args) { diff --git a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java index 55331f2..2061c5a 100644 --- a/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java +++ b/src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java @@ -46,12 +46,11 @@ public void close() { /** * Stored Procedure Example - * + *

* This sample code demonstrates creation, execution, and effects of stored procedures * using Java SDK. A stored procedure is created which will insert a JSON object into * a Cosmos DB container. The sample executes the stored procedure and then performs * a point-read to confirm that the stored procedure had the intended effect. - * */ //

public static void main(String[] args) {