From 5b64114e72f90f0d0c47a95c1ebd1d95db520dfe Mon Sep 17 00:00:00 2001 From: Melanie Date: Wed, 27 May 2020 18:05:38 +0800 Subject: [PATCH 1/3] Update cosmos sample from track1 to track2(Developing a Java app using Azure Cosmos DB Async Java SDK) --- azure-cosmosdb-get-started/pom.xml | 6 +- .../microsoft/azure/cosmosdb/sample/Main.java | 173 +++++++++--------- 2 files changed, 89 insertions(+), 90 deletions(-) diff --git a/azure-cosmosdb-get-started/pom.xml b/azure-cosmosdb-get-started/pom.xml index f54bce5..f9c2dab 100644 --- a/azure-cosmosdb-get-started/pom.xml +++ b/azure-cosmosdb-get-started/pom.xml @@ -41,9 +41,9 @@ - com.microsoft.azure - azure-cosmosdb - 2.2.0 + com.azure + azure-cosmos + 4.0.0-preview.1 org.slf4j diff --git a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Main.java b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Main.java index bb6bf74..5b4204a 100644 --- a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Main.java +++ b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Main.java @@ -23,24 +23,6 @@ package com.microsoft.azure.cosmosdb.sample; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.SqlParameter; -import com.microsoft.azure.cosmosdb.SqlParameterCollection; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import rx.Observable; -import rx.Scheduler; -import rx.schedulers.Schedulers; - import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -50,6 +32,25 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import com.azure.cosmos.ConnectionPolicy; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosClientException; +import com.azure.cosmos.FeedOptions; +import com.azure.cosmos.FeedResponse; +import com.azure.cosmos.SqlParameter; +import com.azure.cosmos.SqlParameterList; +import com.azure.cosmos.SqlQuerySpec; +import com.azure.cosmos.internal.AsyncDocumentClient; +import com.azure.cosmos.internal.Database; +import com.azure.cosmos.internal.Document; +import com.azure.cosmos.internal.DocumentCollection; +import com.azure.cosmos.internal.RequestOptions; +import com.azure.cosmos.internal.ResourceResponse; + +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Scheduler; +import reactor.core.scheduler.Schedulers; + public class Main { private final ExecutorService executorService; private final Scheduler scheduler; @@ -79,7 +80,7 @@ public Main() { // you should provide your own scheduler to switch thread. // the following scheduler is used for switching from netty thread to user app thread. - scheduler = Schedulers.from(executorService); + scheduler = Schedulers.fromExecutor(executorService); } public void close() { @@ -113,9 +114,8 @@ private void getStartedDemo() throws Exception { client = new AsyncDocumentClient.Builder() .withServiceEndpoint(AccountSettings.HOST) .withMasterKeyOrResourceToken(AccountSettings.MASTER_KEY) - .withConnectionPolicy(ConnectionPolicy.GetDefault()) - .withConsistencyLevel(ConsistencyLevel.Eventual) - .build(); + .withConnectionPolicy(ConnectionPolicy.getDefaultPolicy()) + .withConsistencyLevel(ConsistencyLevel.EVENTUAL).build(); createDatabaseIfNotExists(); createDocumentCollectionIfNotExists(); @@ -160,44 +160,42 @@ private void createDatabaseIfNotExists() throws Exception { String databaseLink = String.format("/dbs/%s", databaseName); - Observable> databaseReadObs = - client.readDatabase(databaseLink, null); - - Observable> databaseExistenceObs = - databaseReadObs - .doOnNext(x -> { - System.out.println("database " + databaseName + " already exists."); - }) - .onErrorResumeNext( - e -> { - // if the database doesn't already exists - // readDatabase() will result in 404 error - if (e instanceof DocumentClientException) { - DocumentClientException de = (DocumentClientException) e; - // if database - if (de.getStatusCode() == 404) { - // if the database doesn't exist, create it. - System.out.println("database " + databaseName + " doesn't existed," - + " creating it..."); - - Database dbDefinition = new Database(); - dbDefinition.setId(databaseName); - - return client.createDatabase(dbDefinition, null); - } - } - - // some unexpected failure in reading database happened. - // pass the error up. - System.err.println("Reading database " + databaseName + " failed."); - return Observable.error(e); - }); - + Flux> databaseReadObs = + client.readDatabase(databaseLink, null); + + databaseReadObs + .doOnNext(x -> { + System.out.println("database " + databaseName + " already exists."); + }) + .onErrorResume( + e -> { + // if the database doesn't already exists + // readDatabase() will result in 404 error + if (e instanceof CosmosClientException) { + CosmosClientException de = (CosmosClientException) e; + // if database + if (de.getStatusCode() == 404) { + // if the database doesn't exist, create it. + System.out.println("database " + databaseName + " doesn't existed," + + " creating it..."); + + Database dbDefinition = new Database(); + dbDefinition.setId(databaseName); + + return client.createDatabase(dbDefinition, null); + } + } + + // some unexpected failure in reading database happened. + // pass the error up. + System.err.println("Reading database " + databaseName + " failed."); + return Flux.error(e); + }); // wait for completion, // as waiting for completion is a blocking call try to // provide your own scheduler to avoid stealing netty io threads. - databaseExistenceObs.toCompletable().await(); + Thread.sleep(20000); System.out.println("Checking database " + databaseName + " completed!\n"); } @@ -211,26 +209,27 @@ private void createDocumentCollectionIfNotExists() throws Exception { // if the collection doesn't exist, create it. String databaseLink = String.format("/dbs/%s", databaseName); + + SqlParameterList sqlParameterList=new SqlParameterList(); + sqlParameterList.add(new SqlParameter("@id", collectionName)); + + FeedResponse feedResponsePages = client.queryCollections( + databaseLink, + new SqlQuerySpec("SELECT * FROM r where r.id = @id",sqlParameterList), + null).single().block(); // we know there is only single page of result (empty or with a match) + if (feedResponsePages.getResults().isEmpty()) { + // if there is no matching collection create the collection. + DocumentCollection collection = new DocumentCollection(); + collection.setId(collectionName); + System.out.println("Creating collection " + collectionName); + client.createCollection(databaseLink, collection, null); + } else { + // collection already exists, nothing else to be done. + System.out.println("Collection " + collectionName + "already exists"); + Flux.empty(); + } - client.queryCollections(databaseLink, - new SqlQuerySpec("SELECT * FROM r where r.id = @id", - new SqlParameterCollection( - new SqlParameter("@id", collectionName))), null) - .single() // we know there is only single page of result (empty or with a match) - .flatMap(page -> { - if (page.getResults().isEmpty()) { - // if there is no matching collection create the collection. - DocumentCollection collection = new DocumentCollection(); - collection.setId(collectionName); - System.out.println("Creating collection " + collectionName); - - return client.createCollection(databaseLink, collection, null); - } else { - // collection already exists, nothing else to be done. - System.out.println("Collection " + collectionName + "already exists"); - return Observable.empty(); - } - }).toCompletable().await(); + Thread.sleep(20000); System.out.println("Checking collection " + collectionName + " completed!\n"); } @@ -239,14 +238,14 @@ private void createFamiliesAsyncAndRegisterListener(List families, Count String collectionLink = String.format("/dbs/%s/colls/%s", databaseName, collectionName); - List>> createDocumentsOBs = new ArrayList<>(); + List>> createDocumentsOBs = new ArrayList<>(); for (Family family : families) { - Observable> obs = client.createDocument( + Flux> obs = client.createDocument( collectionLink, family, new RequestOptions(), true); createDocumentsOBs.add(obs); } - Observable.merge(createDocumentsOBs) + Flux.merge(createDocumentsOBs) .map(ResourceResponse::getRequestCharge) .reduce((sum, value) -> sum + value) .subscribe( @@ -271,16 +270,16 @@ private void createFamiliesAsyncAndRegisterListener(List families, Count private void createFamiliesAndWaitForCompletion(List families) throws Exception { String collectionLink = String.format("/dbs/%s/colls/%s", databaseName, collectionName); - List>> createDocumentsOBs = new ArrayList<>(); + List>> createDocumentsOBs = new ArrayList<>(); for (Family family : families) { - Observable> obs = client.createDocument( + Flux> obs = client.createDocument( collectionLink, family, new RequestOptions(), true); createDocumentsOBs.add(obs); } - Double totalRequestCharge = Observable.merge(createDocumentsOBs) + Double totalRequestCharge = Flux.merge(createDocumentsOBs) .map(ResourceResponse::getRequestCharge) - .observeOn(scheduler) // the scheduler will be used for the following work + .subscribeOn(scheduler) // the scheduler will be used for the following work .map(charge -> { // as we don't want to run heavyWork() on netty IO thread, we provide the custom scheduler // for switching from netty IO thread to user thread. @@ -288,7 +287,7 @@ private void createFamiliesAndWaitForCompletion(List families) throws Ex return charge; }) .reduce((sum, value) -> sum + value) - .toBlocking().single(); + .single().block(); writeToConsoleAndPromptToContinue(String.format("Created %d documents with total request charge of %.2f", families.size(), @@ -303,22 +302,23 @@ private void heavyWork() { try { TimeUnit.SECONDS.sleep(2); } catch (Exception e) { + System.out.println("MelanieTest: " + e); } } private void executeSimpleQueryAsyncAndRegisterListenerForResult(CountDownLatch completionLatch) { // Set some common query options FeedOptions queryOptions = new FeedOptions(); - queryOptions.setMaxItemCount(10); + queryOptions.maxItemCount(10); queryOptions.setEnableCrossPartitionQuery(true); String collectionLink = String.format("/dbs/%s/colls/%s", databaseName, collectionName); - Observable> queryObservable = + Flux> queryObservable = client.queryDocuments(collectionLink, "SELECT * FROM Family WHERE Family.lastName != 'Andersen'", queryOptions); queryObservable - .observeOn(scheduler) + .subscribeOn(scheduler) .subscribe( page -> { // we want to make sure heavyWork() doesn't block any of netty IO threads @@ -329,7 +329,6 @@ private void executeSimpleQueryAsyncAndRegisterListenerForResult(CountDownLatch page.getResults().size() + " document(s)" + " and request charge of " + page.getRequestCharge()); - System.out.println("Document Ids " + page.getResults().stream().map(d -> d.getId()) .collect(Collectors.toList())); }, From 0915a4a3e56cfe6d814de434587d3e49546c9538 Mon Sep 17 00:00:00 2001 From: Melanie Date: Thu, 26 Nov 2020 13:50:14 +0800 Subject: [PATCH 2/3] update --- azure-cosmosdb-get-started/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azure-cosmosdb-get-started/pom.xml b/azure-cosmosdb-get-started/pom.xml index f9c2dab..f98ac1a 100644 --- a/azure-cosmosdb-get-started/pom.xml +++ b/azure-cosmosdb-get-started/pom.xml @@ -43,7 +43,7 @@ com.azure azure-cosmos - 4.0.0-preview.1 + 4.8.0 org.slf4j From 1d723517491926ebef52ba8bd0ad7677d094221e Mon Sep 17 00:00:00 2001 From: Melanie Date: Fri, 11 Dec 2020 14:35:52 +0800 Subject: [PATCH 3/3] update for the comments --- .github/ISSUE_TEMPLATE.md | 33 -- .github/PULL_REQUEST_TEMPLATE.md | 45 --- .gitignore | 28 -- CONTRIBUTING.md | 76 ---- LICENSE.md | 21 -- README.md | 14 +- azure-cosmosdb-get-started/pom.xml | 59 --- .../cosmosdb/sample/AccountSettings.java | 59 --- .../azure/cosmosdb/sample/Address.java | 55 --- .../azure/cosmosdb/sample/Child.java | 73 ---- .../azure/cosmosdb/sample/Families.java | 136 ------- .../azure/cosmosdb/sample/Family.java | 94 ----- .../microsoft/azure/cosmosdb/sample/Main.java | 352 ------------------ .../azure/cosmosdb/sample/Parent.java | 53 --- .../microsoft/azure/cosmosdb/sample/Pet.java | 36 -- .../src/main/resources/log4j.properties | 15 - 16 files changed, 2 insertions(+), 1147 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE.md delete mode 100644 .github/PULL_REQUEST_TEMPLATE.md delete mode 100644 .gitignore delete mode 100644 CONTRIBUTING.md delete mode 100644 LICENSE.md delete mode 100644 azure-cosmosdb-get-started/pom.xml delete mode 100644 azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/AccountSettings.java delete mode 100644 azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Address.java delete mode 100644 azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Child.java delete mode 100644 azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Families.java delete mode 100644 azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Family.java delete mode 100644 azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Main.java delete mode 100644 azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Parent.java delete mode 100644 azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Pet.java delete mode 100644 azure-cosmosdb-get-started/src/main/resources/log4j.properties diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 15c7f60..0000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,33 +0,0 @@ - -> Please provide us with the following information: -> --------------------------------------------------------------- - -### This issue is for a: (mark with an `x`) -``` -- [ ] bug report -> please search issues before submitting -- [ ] feature request -- [ ] documentation issue or request -- [ ] regression (a behavior that used to work and stopped in a new release) -``` - -### Minimal steps to reproduce -> - -### Any log messages given by the failure -> - -### Expected/desired behavior -> - -### OS and Version? -> Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?) - -### Versions -> - -### Mention any other details that might be useful - -> --------------------------------------------------------------- -> Thanks! We'll be in touch soon. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index ab05e29..0000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,45 +0,0 @@ -## Purpose - -* ... - -## Does this introduce a breaking change? - -``` -[ ] Yes -[ ] No -``` - -## Pull Request Type -What kind of change does this Pull Request introduce? - - -``` -[ ] Bugfix -[ ] Feature -[ ] Code style update (formatting, local variables) -[ ] Refactoring (no functional changes, no api changes) -[ ] Documentation content changes -[ ] Other... Please describe: -``` - -## How to Test -* Get the code - -``` -git clone [repo-address] -cd [repo-name] -git checkout [branch-name] -npm install -``` - -* Test the code - -``` -``` - -## What to Check -Verify that the following are valid -* ... - -## Other Information - \ No newline at end of file diff --git a/.gitignore b/.gitignore deleted file mode 100644 index a9b35aa..0000000 --- a/.gitignore +++ /dev/null @@ -1,28 +0,0 @@ -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# eclipse -.classpath -.project -.settings/ -target/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 4bd3eba..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,76 +0,0 @@ -# Contributing to [project-title] - -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.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., label, 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. - - - [Code of Conduct](#coc) - - [Issues and Bugs](#issue) - - [Feature Requests](#feature) - - [Submission Guidelines](#submit) - -## Code of Conduct -Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/). - -## Found an Issue? -If you find a bug in the source code or a mistake in the documentation, you can help us by -[submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can -[submit a Pull Request](#submit-pr) with a fix. - -## Want a Feature? -You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub -Repository. If you would like to *implement* a new feature, please submit an issue with -a proposal for your work first, to be sure that we can use it. - -* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). - -## Submission Guidelines - -### Submitting an Issue -Before you submit an issue, search the archive, maybe your question was already answered. - -If your issue appears to be a bug, and hasn't been reported, open a new issue. -Help us to maximize the effort we can spend fixing issues and adding new -features, by not reporting duplicate issues. Providing the following information will increase the -chances of your issue being dealt with quickly: - -* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps -* **Version** - what version is affected (e.g. 0.1.2) -* **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you -* **Browsers and Operating System** - is this a problem with all browsers? -* **Reproduce the Error** - provide a live example or a unambiguous set of steps -* **Related Issues** - has a similar issue been reported before? -* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be - causing the problem (line of code or commit) - -You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new]. - -### Submitting a Pull Request (PR) -Before you submit your Pull Request (PR) consider the following guidelines: - -* Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR - that relates to your submission. You don't want to duplicate effort. - -* Make your changes in a new git fork: - -* Commit your changes using a descriptive commit message -* Push your fork to GitHub: -* In GitHub, create a pull request -* If we suggest changes then: - * Make the required updates. - * Rebase your fork and force push to your GitHub repository (this will update your Pull Request): - - ```shell - git rebase master -i - git push -f - ``` - -That's it! Thank you for your contribution! diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index d1ca00f..0000000 --- a/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ - MIT License - - Copyright (c) Microsoft Corporation. All rights reserved. - - 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 \ No newline at end of file diff --git a/README.md b/README.md index 7650e1a..ce3508a 100644 --- a/README.md +++ b/README.md @@ -28,22 +28,12 @@ Azure Cosmos DB is a globally distributed multi-model database. One of the suppo * Then, clone this repository using ```bash -git clone https://github.com/Azure-Samples/azure-cosmos-db-sql-api-async-java-getting-started.git +git clone https://github.com/Azure-Samples/azure-cosmos-java-getting-started.git ``` -* From a command prompt or shell, run the following command to compile and resolve dependencies. +* More [Cosmos samples](https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples). -```bash -cd azure-cosmos-db-sql-api-async-java-getting-started -cd azure-cosmosdb-get-started -mvn clean package -``` - -* From a command prompt or shell, run the following command to run the application. -```bash -mvn exec:java -DACCOUNT_HOST=YOUR_COSMOS_DB_HOSTNAME -DACCOUNT_KEY=YOUR_COSMOS_DB_MASTER_KEY -``` ## About the code diff --git a/azure-cosmosdb-get-started/pom.xml b/azure-cosmosdb-get-started/pom.xml deleted file mode 100644 index f98ac1a..0000000 --- a/azure-cosmosdb-get-started/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - 4.0.0 - com.microsoft.azure - azure-cosmosdb-get-started - 1.0.0-SNAPSHOT - Get Started With 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 - - com.microsoft.azure.cosmosdb.sample.Main - - - - 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.8.0 - - - org.slf4j - slf4j-log4j12 - 1.7.6 - - - log4j - log4j - 1.2.17 - - - diff --git a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/AccountSettings.java b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/AccountSettings.java deleted file mode 100644 index 347a256..0000000 --- a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/AccountSettings.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * The MIT License (MIT) - * Copyright (c) 2018 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. - */ -package com.microsoft.azure.cosmosdb.sample; - -import org.apache.commons.lang3.StringUtils; - -/** - * Contains the account configurations for Sample. - * - * For running tests, you can pass a customized endpoint configuration in one of the following - * ways: - *
    - *
  • -DACCOUNT_KEY="[your-key]" -ACCOUNT_HOST="[your-endpoint]" as JVM - * command-line option.
  • - *
  • You can set ACCOUNT_KEY and ACCOUNT_HOST as environment variables.
  • - *
- * - * If none of the above is set, emulator endpoint will be used. - * Emulator http cert is self signed. If you are using emulator, - * make sure emulator https certificate is imported - * to java trusted cert store: - * https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator-export-ssl-certificates - */ -public class AccountSettings { - // Replace MASTER_KEY and HOST with values from your Azure Cosmos DB account. - // The default values are credentials of the local emulator, which are not used in any production environment. - // - public static String MASTER_KEY = - System.getProperty("ACCOUNT_KEY", - StringUtils.defaultString(StringUtils.trimToNull( - System.getenv().get("ACCOUNT_KEY")), - "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")); - - public static String HOST = - System.getProperty("ACCOUNT_HOST", - StringUtils.defaultString(StringUtils.trimToNull( - System.getenv().get("ACCOUNT_HOST")), - "https://localhost:443/")); -} diff --git a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Address.java b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Address.java deleted file mode 100644 index 68def20..0000000 --- a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Address.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * The MIT License (MIT) - * Copyright (c) 2018 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. - */ - -package com.microsoft.azure.cosmosdb.sample; - -public class Address { - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getCounty() { - return county; - } - - public void setCounty(String county) { - this.county = county; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - private String state; - private String county; - private String city; -} - diff --git a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Child.java b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Child.java deleted file mode 100644 index a3180a2..0000000 --- a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Child.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * The MIT License (MIT) - * Copyright (c) 2018 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. - */ - -package com.microsoft.azure.cosmosdb.sample; - -public class Child { - public String getFamilyName() { - return familyName; - } - - public void setFamilyName(String familyName) { - this.familyName = familyName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public int getGrade() { - return grade; - } - - public void setGrade(int grade) { - this.grade = grade; - } - - public Pet[] getPets() { - return pets; - } - - public void setPets(Pet[] pets) { - this.pets = pets; - } - - private String familyName; - private String firstName; - private String gender; - private int grade; - private Pet[] pets; -} - diff --git a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Families.java b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Families.java deleted file mode 100644 index ff0ced1..0000000 --- a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Families.java +++ /dev/null @@ -1,136 +0,0 @@ -/** - * The MIT License (MIT) - * Copyright (c) 2018 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. - */ -package com.microsoft.azure.cosmosdb.sample; - -public class Families { - - public static Family getAndersenFamilyDocument() { - Family andersenFamily = new Family(); - andersenFamily.setId("Andersen-" + System.currentTimeMillis()); - andersenFamily.setLastName("Andersen"); - - Parent parent1 = new Parent(); - parent1.setFirstName("Thomas"); - - Parent parent2 = new Parent(); - parent2.setFirstName("Mary Kay"); - - andersenFamily.setParents(new Parent[] { parent1, parent2 }); - - Child child1 = new Child(); - child1.setFirstName("Henriette Thaulow"); - child1.setGender("female"); - child1.setGrade(5); - - Pet pet1 = new Pet(); - pet1.setGivenName("Fluffy"); - - child1.setPets(new Pet[] { pet1 }); - - andersenFamily.setDistrict("WA5"); - Address address = new Address(); - address.setCity("Seattle"); - address.setCounty("King"); - address.setState("WA"); - - andersenFamily.setAddress(address); - andersenFamily.setRegistered(true); - - return andersenFamily; - } - - public static Family getWakefieldFamilyDocument() { - Family wakefieldFamily = new Family(); - wakefieldFamily.setId("Wakefield-" + System.currentTimeMillis()); - wakefieldFamily.setLastName("Wakefield"); - - Parent parent1 = new Parent(); - parent1.setFamilyName("Wakefield"); - parent1.setFirstName("Robin"); - - Parent parent2 = new Parent(); - parent2.setFamilyName("Miller"); - parent2.setFirstName("Ben"); - - wakefieldFamily.setParents(new Parent[] { parent1, parent2 }); - - Child child1 = new Child(); - child1.setFirstName("Jesse"); - child1.setFamilyName("Merriam"); - child1.setGrade(8); - - Pet pet1 = new Pet(); - pet1.setGivenName("Goofy"); - - Pet pet2 = new Pet(); - pet2.setGivenName("Shadow"); - - child1.setPets(new Pet[] { pet1, pet2 }); - - Child child2 = new Child(); - child2.setFirstName("Lisa"); - child2.setFamilyName("Miller"); - child2.setGrade(1); - child2.setGender("female"); - - wakefieldFamily.setChildren(new Child[] { child1, child2 }); - - Address address = new Address(); - address.setCity("NY"); - address.setCounty("Manhattan"); - address.setState("NY"); - - wakefieldFamily.setAddress(address); - wakefieldFamily.setDistrict("NY23"); - wakefieldFamily.setRegistered(true); - return wakefieldFamily; - } - - public static Family getJohnsonFamilyDocument() { - Family andersenFamily = new Family(); - andersenFamily.setId("Johnson-" + System.currentTimeMillis()); - andersenFamily.setLastName("Johnson"); - - Parent parent1 = new Parent(); - parent1.setFirstName("John"); - - Parent parent2 = new Parent(); - parent2.setFirstName("Lili"); - - return andersenFamily; - } - - public static Family getSmithFamilyDocument() { - Family andersenFamily = new Family(); - andersenFamily.setId("Smith-" + System.currentTimeMillis()); - andersenFamily.setLastName("Smith"); - - Parent parent1 = new Parent(); - parent1.setFirstName("John"); - - Parent parent2 = new Parent(); - parent2.setFirstName("Cynthia"); - - return andersenFamily; - } -} diff --git a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Family.java b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Family.java deleted file mode 100644 index b300508..0000000 --- a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Family.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * The MIT License (MIT) - * Copyright (c) 2018 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. - */ - -package com.microsoft.azure.cosmosdb.sample; - -public class Family { - public Family() { - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getDistrict() { - return district; - } - - public void setDistrict(String district) { - this.district = district; - } - - public Parent[] getParents() { - return parents; - } - - public void setParents(Parent[] parents) { - this.parents = parents; - } - - public Child[] getChildren() { - return children; - } - - public void setChildren(Child[] children) { - this.children = children; - } - - public Address getAddress() { - return address; - } - - public void setAddress(Address address) { - this.address = address; - } - - public boolean isRegistered() { - return isRegistered; - } - - public void setRegistered(boolean isRegistered) { - this.isRegistered = isRegistered; - } - - private String id; - private String lastName; - private String district; - private Parent[] parents; - private Child[] children; - private Address address; - private boolean isRegistered; -} - diff --git a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Main.java b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Main.java deleted file mode 100644 index 5b4204a..0000000 --- a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Main.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 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. - */ - -package com.microsoft.azure.cosmosdb.sample; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import com.azure.cosmos.ConnectionPolicy; -import com.azure.cosmos.ConsistencyLevel; -import com.azure.cosmos.CosmosClientException; -import com.azure.cosmos.FeedOptions; -import com.azure.cosmos.FeedResponse; -import com.azure.cosmos.SqlParameter; -import com.azure.cosmos.SqlParameterList; -import com.azure.cosmos.SqlQuerySpec; -import com.azure.cosmos.internal.AsyncDocumentClient; -import com.azure.cosmos.internal.Database; -import com.azure.cosmos.internal.Document; -import com.azure.cosmos.internal.DocumentCollection; -import com.azure.cosmos.internal.RequestOptions; -import com.azure.cosmos.internal.ResourceResponse; - -import reactor.core.publisher.Flux; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; - -public class Main { - private final ExecutorService executorService; - private final Scheduler scheduler; - - private AsyncDocumentClient client; - - private final String databaseName = "AzureSampleFamilyDB"; - private final String collectionName = "FamilyCollection"; - - public Main() { - executorService = Executors.newFixedThreadPool(100); - // The SDK uses netty library for doing async IO operations. The IO operations are performed on the netty io threads. - // The number of IO netty threads are limited; it is the same as the number of CPU cores. - - // The app should avoid doing anything which takes a lot of time from IO netty thread. - // If the app consumes too much of IO netty thread you may face: - // * low throughput - // * bad latency - // * ReadTimeoutException because there is no netty IO thread available to read data from network. - // * deadlock - - // The app code will receive the data from Azure Cosmos DB on the netty IO thread. - // The app should ensure the user's computationally/IO heavy work after receiving data - // from Azure Cosmos DB is performed on a custom thread managed by the user (not on the SDK netty IO thread). - // - // If you are doing heavy work after receiving the result from the SDK, - // you should provide your own scheduler to switch thread. - - // the following scheduler is used for switching from netty thread to user app thread. - scheduler = Schedulers.fromExecutor(executorService); - } - - public void close() { - executorService.shutdown(); - client.close(); - } - - /** - * Run a Hello DocumentDB console application. - * - * @param args command line args. - */ - public static void main(String[] args) { - Main p = new Main(); - - try { - p.getStartedDemo(); - System.out.println(String.format("Demo complete, please hold while resources are released")); - } catch (Exception e) { - System.err.println(String.format("DocumentDB GetStarted failed with %s", e)); - } finally { - System.out.println("close the client"); - p.close(); - } - System.exit(0); - } - - private void getStartedDemo() throws Exception { - System.out.println("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST); - - client = new AsyncDocumentClient.Builder() - .withServiceEndpoint(AccountSettings.HOST) - .withMasterKeyOrResourceToken(AccountSettings.MASTER_KEY) - .withConnectionPolicy(ConnectionPolicy.getDefaultPolicy()) - .withConsistencyLevel(ConsistencyLevel.EVENTUAL).build(); - - createDatabaseIfNotExists(); - createDocumentCollectionIfNotExists(); - - Family andersenFamily = Families.getAndersenFamilyDocument(); - Family wakefieldFamily = Families.getWakefieldFamilyDocument(); - - ArrayList familiesToCreate = new ArrayList<>(); - familiesToCreate.add(andersenFamily); - familiesToCreate.add(wakefieldFamily); - - createFamiliesAndWaitForCompletion(familiesToCreate); - - familiesToCreate = new ArrayList<>(); - familiesToCreate.add(Families.getJohnsonFamilyDocument()); - familiesToCreate.add(Families.getSmithFamilyDocument()); - - CountDownLatch createDocumentsCompletionLatch = new CountDownLatch(1); - - System.out.println("Creating documents async and registering listener for the completion."); - createFamiliesAsyncAndRegisterListener(familiesToCreate, createDocumentsCompletionLatch); - - CountDownLatch queryCompletionLatch = new CountDownLatch(1); - - System.out.println("Querying documents async and registering listener for the result."); - executeSimpleQueryAsyncAndRegisterListenerForResult(queryCompletionLatch); - - // as createFamiliesAsyncAndRegisterListener starts the operation in background - // and only registers a listener, we used the createDocumentsCompletionLatch - // to ensure we wait for the completion - createDocumentsCompletionLatch.await(); - - // as executeSimpleQueryAsyncAndRegisterListenerForResult starts the operation in background - // and only registers a listener, we used the queryCompletionLatch - // to ensure we wait for the completion - queryCompletionLatch.await(); - } - - private void createDatabaseIfNotExists() throws Exception { - writeToConsoleAndPromptToContinue( - "Check if database " + databaseName + " exists."); - - String databaseLink = String.format("/dbs/%s", databaseName); - - Flux> databaseReadObs = - client.readDatabase(databaseLink, null); - - databaseReadObs - .doOnNext(x -> { - System.out.println("database " + databaseName + " already exists."); - }) - .onErrorResume( - e -> { - // if the database doesn't already exists - // readDatabase() will result in 404 error - if (e instanceof CosmosClientException) { - CosmosClientException de = (CosmosClientException) e; - // if database - if (de.getStatusCode() == 404) { - // if the database doesn't exist, create it. - System.out.println("database " + databaseName + " doesn't existed," - + " creating it..."); - - Database dbDefinition = new Database(); - dbDefinition.setId(databaseName); - - return client.createDatabase(dbDefinition, null); - } - } - - // some unexpected failure in reading database happened. - // pass the error up. - System.err.println("Reading database " + databaseName + " failed."); - return Flux.error(e); - }); - - // wait for completion, - // as waiting for completion is a blocking call try to - // provide your own scheduler to avoid stealing netty io threads. - Thread.sleep(20000); - - System.out.println("Checking database " + databaseName + " completed!\n"); - } - - private void createDocumentCollectionIfNotExists() throws Exception { - writeToConsoleAndPromptToContinue( - "Check if collection " + collectionName + " exists."); - - // query for a collection with a given id - // if it exists nothing else to be done - // if the collection doesn't exist, create it. - - String databaseLink = String.format("/dbs/%s", databaseName); - - SqlParameterList sqlParameterList=new SqlParameterList(); - sqlParameterList.add(new SqlParameter("@id", collectionName)); - - FeedResponse feedResponsePages = client.queryCollections( - databaseLink, - new SqlQuerySpec("SELECT * FROM r where r.id = @id",sqlParameterList), - null).single().block(); // we know there is only single page of result (empty or with a match) - if (feedResponsePages.getResults().isEmpty()) { - // if there is no matching collection create the collection. - DocumentCollection collection = new DocumentCollection(); - collection.setId(collectionName); - System.out.println("Creating collection " + collectionName); - client.createCollection(databaseLink, collection, null); - } else { - // collection already exists, nothing else to be done. - System.out.println("Collection " + collectionName + "already exists"); - Flux.empty(); - } - - Thread.sleep(20000); - - System.out.println("Checking collection " + collectionName + " completed!\n"); - } - - private void createFamiliesAsyncAndRegisterListener(List families, CountDownLatch completionLatch) { - - String collectionLink = String.format("/dbs/%s/colls/%s", databaseName, collectionName); - - List>> createDocumentsOBs = new ArrayList<>(); - for (Family family : families) { - Flux> obs = client.createDocument( - collectionLink, family, new RequestOptions(), true); - createDocumentsOBs.add(obs); - } - - Flux.merge(createDocumentsOBs) - .map(ResourceResponse::getRequestCharge) - .reduce((sum, value) -> sum + value) - .subscribe( - totalRequestCharge -> { - // this will get print out when completed - System.out.println("total charge for creating documents is " - + totalRequestCharge); - }, - - // terminal error signal - e -> { - e.printStackTrace(); - completionLatch.countDown(); - }, - - // terminal completion signal - () -> { - completionLatch.countDown(); - }); - } - - private void createFamiliesAndWaitForCompletion(List families) throws Exception { - String collectionLink = String.format("/dbs/%s/colls/%s", databaseName, collectionName); - - List>> createDocumentsOBs = new ArrayList<>(); - for (Family family : families) { - Flux> obs = client.createDocument( - collectionLink, family, new RequestOptions(), true); - createDocumentsOBs.add(obs); - } - - Double totalRequestCharge = Flux.merge(createDocumentsOBs) - .map(ResourceResponse::getRequestCharge) - .subscribeOn(scheduler) // the scheduler will be used for the following work - .map(charge -> { - // as we don't want to run heavyWork() on netty IO thread, we provide the custom scheduler - // for switching from netty IO thread to user thread. - heavyWork(); - return charge; - }) - .reduce((sum, value) -> sum + value) - .single().block(); - - writeToConsoleAndPromptToContinue(String.format("Created %d documents with total request charge of %.2f", - families.size(), - totalRequestCharge)); - } - - private void heavyWork() { - // I may do a lot of IO work: e.g., writing to log files - // a lot of computational work - // or may do Thread.sleep() - - try { - TimeUnit.SECONDS.sleep(2); - } catch (Exception e) { - System.out.println("MelanieTest: " + e); - } - } - - private void executeSimpleQueryAsyncAndRegisterListenerForResult(CountDownLatch completionLatch) { - // Set some common query options - FeedOptions queryOptions = new FeedOptions(); - queryOptions.maxItemCount(10); - queryOptions.setEnableCrossPartitionQuery(true); - - String collectionLink = String.format("/dbs/%s/colls/%s", databaseName, collectionName); - Flux> queryObservable = - client.queryDocuments(collectionLink, - "SELECT * FROM Family WHERE Family.lastName != 'Andersen'", queryOptions); - - queryObservable - .subscribeOn(scheduler) - .subscribe( - page -> { - // we want to make sure heavyWork() doesn't block any of netty IO threads - // so we use observeOn(scheduler) to switch from the netty thread to user's thread. - heavyWork(); - - System.out.println("Got a page of query result with " + - page.getResults().size() + " document(s)" - + " and request charge of " + page.getRequestCharge()); - - System.out.println("Document Ids " + page.getResults().stream().map(d -> d.getId()) - .collect(Collectors.toList())); - }, - // terminal error signal - e -> { - e.printStackTrace(); - completionLatch.countDown(); - }, - - // terminal completion signal - () -> { - completionLatch.countDown(); - }); - } - - private void writeToConsoleAndPromptToContinue(String text) throws IOException { - System.out.println(text); - System.out.println("Press any key to continue ..."); - System.in.read(); - } -} diff --git a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Parent.java b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Parent.java deleted file mode 100644 index 0df7dd8..0000000 --- a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Parent.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * The MIT License (MIT) - * Copyright (c) 2018 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. - */ - -package com.microsoft.azure.cosmosdb.sample; - -public class Parent { - - public Parent() { - } - - public Parent(String firstName) { - this.firstName = firstName; - } - - public String getFamilyName() { - return familyName; - } - - public void setFamilyName(String familyName) { - this.familyName = familyName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - private String familyName; - private String firstName; -} diff --git a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Pet.java b/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Pet.java deleted file mode 100644 index 3a6d392..0000000 --- a/azure-cosmosdb-get-started/src/main/java/com/microsoft/azure/cosmosdb/sample/Pet.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * The MIT License (MIT) - * Copyright (c) 2018 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. - */ - -package com.microsoft.azure.cosmosdb.sample; - -public class Pet { - public String getGivenName() { - return givenName; - } - - public void setGivenName(String givenName) { - this.givenName = givenName; - } - - private String givenName; -} diff --git a/azure-cosmosdb-get-started/src/main/resources/log4j.properties b/azure-cosmosdb-get-started/src/main/resources/log4j.properties deleted file mode 100644 index 81050c5..0000000 --- a/azure-cosmosdb-get-started/src/main/resources/log4j.properties +++ /dev/null @@ -1,15 +0,0 @@ -# this is the log4j configuration for tests - -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=WARN, A1 - -# Set HTTP components' logger to INFO - -log4j.category.io.netty=INFO -log4j.category.io.reactivex=INFO -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%d %5X{pid} [%t] %-5p %c - %m%n