diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index c72a574..f9ba8cf 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,9 +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 +# 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 index 3d8b93b..9e841e7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +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 + 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 index 829a2ee..4ad3657 100644 --- a/README.md +++ b/README.md @@ -1,101 +1,98 @@ ---- -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. +--- +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 + +* 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 + +These environment variables must be set + +``` +ACCOUNT_HOST=your account hostname;ACCOUNT_KEY=your account master key +``` + +in order to give the samples read/write access to your account. + +To run a sample, specify its Main Class + +``` +com.azure.cosmos.examples.sample.synchronicity.MainClass +``` + +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: +``` +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 index 7ab49eb..e0dfff5 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,41 +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). - - + + +## 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 index 57eb621..69ece04 100644 --- a/pom.xml +++ b/pom.xml @@ -1,83 +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 - - - - 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 - - - + 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 - - - 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 - - + + + + + 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 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..5c07fea 100644 --- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java +++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java @@ -5,16 +5,16 @@ 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.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; @@ -28,7 +28,12 @@ /** * 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 { @@ -42,30 +47,24 @@ 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 { - //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"); + 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: *

- * + *

* 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 3e5b581..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 @@ -4,12 +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.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; @@ -17,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; @@ -38,22 +50,29 @@ 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) { 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(); } } @@ -61,16 +80,8 @@ 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. - 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 @@ -80,27 +91,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); @@ -109,36 +120,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 // @@ -149,7 +160,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(); @@ -164,42 +175,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.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. + 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); } // @@ -207,7 +220,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 @@ -215,7 +228,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(); @@ -230,36 +243,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", - 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();} - ); + 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(); + 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); } // @@ -270,73 +285,75 @@ 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( - "SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class); + CosmosPagedFlux 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(); - } + 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 293cd35..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 @@ -9,27 +9,26 @@ 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.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.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; @@ -48,22 +47,29 @@ 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) { 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"); + 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(); } } @@ -71,16 +77,8 @@ 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. - 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 @@ -90,11 +88,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(); // @@ -112,40 +110,40 @@ 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 // CosmosContainerProperties containerProperties = - new CosmosContainerProperties(containerName, "/lastName"); + 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"); + logger.info("Checking container " + container.getId() + " completed!\n"); } private void createFamilies(List families) throws Exception { @@ -162,22 +160,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", - item.getRequestCharge(), item.getRequestLatency())); + 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", - families.size(), totalRequestCharge)); + 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())); } @@ -190,11 +188,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", - item.getResource().getId(), requestCharge, requestLatency)); + 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)); } // }); @@ -204,48 +202,48 @@ 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 -> { - 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())); + logger.info("Got a page of query result with " + + cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)" + + " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()); + + logger.info("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()); + 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..."); + 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 b335434..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 @@ -3,12 +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.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; @@ -18,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; @@ -39,22 +55,24 @@ 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) { 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(); } } @@ -62,11 +80,8 @@ 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. - 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 @@ -89,10 +104,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, @@ -107,29 +122,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 // @@ -197,7 +212,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(); @@ -215,25 +230,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.getResource().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(); @@ -241,13 +256,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); } // @@ -268,15 +285,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", - itemResponse.getResource().getId(), requestCharge, requestLatency)); + 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(); @@ -284,13 +301,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); } // @@ -301,22 +320,22 @@ 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); 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) @@ -325,9 +344,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(); @@ -335,13 +354,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); } // @@ -350,19 +371,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 fc07cab..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 @@ -3,18 +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.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; @@ -36,8 +51,10 @@ 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) { @@ -45,14 +62,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(); } } @@ -60,11 +77,8 @@ 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. - 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 @@ -96,26 +110,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 = @@ -180,7 +194,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 { @@ -197,12 +211,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)); @@ -217,11 +231,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)); } // }); @@ -231,19 +245,19 @@ 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 -> { - 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) @@ -255,19 +269,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 2ac24fb..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 @@ -2,23 +2,33 @@ // 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.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.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.Flux; import reactor.core.publisher.Mono; -import java.util.UUID; import java.util.concurrent.CountDownLatch; public class SampleStoredProcedureAsync { @@ -40,9 +50,12 @@ public void close() { } /** - * Run a Hello CosmosDB console application. - * - * @param args command line args. + * 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) { @@ -50,12 +63,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 { } @@ -76,15 +89,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 @@ -94,25 +107,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 { @@ -121,87 +134,89 @@ 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 { FeedOptions feedOptions = new FeedOptions(); - CosmosContinuablePagedFlux fluxResponse = + CosmosPagedFlux 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())); + 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 fe96c54..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 @@ -3,17 +3,27 @@ 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.implementation.Utils; -import com.fasterxml.jackson.databind.ObjectMapper; +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; -import java.util.UUID; import java.util.Iterator; public class SampleStoredProcedure { @@ -35,9 +45,12 @@ public void close() { } /** - * Run a Hello CosmosDB console application. - * - * @param args command line args. + * 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) { @@ -45,12 +58,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 { } @@ -59,26 +72,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 @@ -88,19 +101,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 { @@ -109,66 +122,66 @@ 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(); - CosmosContinuablePagedIterable feedResponseIterable = + CosmosPagedIterable feedResponseIterable = container.getScripts().readAllStoredProcedures(feedOptions); 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 43f940f..f1178ab 100644 --- a/src/main/resources/log4j2.properties +++ b/src/main/resources/log4j2.properties @@ -1,21 +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.reactor.name = io.reactivex -logger.reactor.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