docs) -> {
+ logger.info("--->setHandleChanges() START");
+
+ for (JsonNode document : docs) {
+ try {
+ //Change Feed hands the document to you in the form of a JsonNode
+ //As a developer you have two options for handling the JsonNode document provided to you by Change Feed
+ //One option is to operate on the document in the form of a JsonNode, as shown below. This is great
+ //especially if you do not have a single uniform data model for all documents.
+ logger.info("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter()
+ .writeValueAsString(document));
+
+ //You can also transform the JsonNode to a POJO having the same structure as the JsonNode,
+ //as shown below. Then you can operate on the POJO.
+ CustomPOJO pojo_doc = OBJECT_MAPPER.treeToValue(document, CustomPOJO.class);
+ logger.info("----=>id: " + pojo_doc.getId());
+
+ } catch (JsonProcessingException e) {
+ e.printStackTrace();
+ }
}
- }
- System.out.println("--->handleChanges() END");
+ logger.info("--->handleChanges() END");
- })
- .build();
+ })
+ .build();
}
public static CosmosAsyncClient getCosmosClient() {
@@ -236,7 +235,7 @@ public static CosmosAsyncContainer createNewLeaseCollection(CosmosAsyncClient cl
CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id");
CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions();
- leaseContainerResponse = databaseLink.createContainer(containerSettings, 400,requestOptions).block();
+ leaseContainerResponse = databaseLink.createContainer(containerSettings, 400, requestOptions).block();
if (leaseContainerResponse == null) {
throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName));
@@ -252,7 +251,7 @@ public static void createNewDocumentsCustomPOJO(CosmosAsyncContainer containerCl
document.setId(String.format("0%d-%s", i, suffix));
containerClient.createItem(document).subscribe(doc -> {
- System.out.println("---->DOCUMENT WRITE: " + doc);
+ logger.info("---->DOCUMENT WRITE: " + doc);
});
long remainingWork = delay.toMillis();
diff --git a/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java b/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java
index 86e75c7..f373f7e 100644
--- a/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java
+++ b/src/main/java/com/azure/cosmos/examples/changefeed/SampleConfigurations.java
@@ -23,14 +23,14 @@ public final class SampleConfigurations {
// The default values are credentials of the local emulator, which are not used in any production environment.
//
public static String MASTER_KEY =
- System.getProperty("ACCOUNT_KEY",
- StringUtils.defaultString(Strings.emptyToNull(
- System.getenv().get("ACCOUNT_KEY")),
- "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="));
+ System.getProperty("ACCOUNT_KEY",
+ StringUtils.defaultString(Strings.emptyToNull(
+ System.getenv().get("ACCOUNT_KEY")),
+ "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="));
public static String HOST =
- System.getProperty("ACCOUNT_HOST",
- StringUtils.defaultString(Strings.emptyToNull(
- System.getenv().get("ACCOUNT_HOST")),
- "https://localhost:8081/"));
+ System.getProperty("ACCOUNT_HOST",
+ StringUtils.defaultString(Strings.emptyToNull(
+ System.getenv().get("ACCOUNT_HOST")),
+ "https://localhost:8081/"));
}
diff --git a/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java b/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java
index 12bb3ba..64a7776 100644
--- a/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java
+++ b/src/main/java/com/azure/cosmos/examples/common/AccountSettings.java
@@ -7,7 +7,7 @@
/**
* Contains the account configurations for Sample.
- *
+ *
* For running tests, you can pass a customized endpoint configuration in one of the following
* ways:
*
@@ -15,7 +15,7 @@
* command-line option.
* - You can set ACCOUNT_KEY and ACCOUNT_HOST as environment variables.
*
- *
+ *
* If none of the above is set, emulator endpoint will be used.
* Emulator http cert is self signed. If you are using emulator,
* make sure emulator https certificate is imported
diff --git a/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java b/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java
index 7704081..0341d1a 100644
--- a/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java
+++ b/src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java
@@ -1,3 +1,6 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
package com.azure.cosmos.examples.common;
public class CustomPOJO {
@@ -8,7 +11,7 @@ public CustomPOJO() {
}
public CustomPOJO(String id) {
- this.id=id;
+ this.id = id;
}
public String getId() {
diff --git a/src/main/java/com/azure/cosmos/examples/common/Families.java b/src/main/java/com/azure/cosmos/examples/common/Families.java
index fd549ee..1f658ae 100644
--- a/src/main/java/com/azure/cosmos/examples/common/Families.java
+++ b/src/main/java/com/azure/cosmos/examples/common/Families.java
@@ -16,7 +16,7 @@ public static Family getAndersenFamilyItem() {
Parent parent2 = new Parent();
parent2.setFirstName("Mary Kay");
- andersenFamily.setParents(new Parent[] { parent1, parent2 });
+ andersenFamily.setParents(new Parent[]{parent1, parent2});
Child child1 = new Child();
child1.setFirstName("Henriette Thaulow");
@@ -26,7 +26,7 @@ public static Family getAndersenFamilyItem() {
Pet pet1 = new Pet();
pet1.setGivenName("Fluffy");
- child1.setPets(new Pet[] { pet1 });
+ child1.setPets(new Pet[]{pet1});
andersenFamily.setDistrict("WA5");
Address address = new Address();
@@ -53,7 +53,7 @@ public static Family getWakefieldFamilyItem() {
parent2.setFamilyName("Miller");
parent2.setFirstName("Ben");
- wakefieldFamily.setParents(new Parent[] { parent1, parent2 });
+ wakefieldFamily.setParents(new Parent[]{parent1, parent2});
Child child1 = new Child();
child1.setFirstName("Jesse");
@@ -66,7 +66,7 @@ public static Family getWakefieldFamilyItem() {
Pet pet2 = new Pet();
pet2.setGivenName("Shadow");
- child1.setPets(new Pet[] { pet1, pet2 });
+ child1.setPets(new Pet[]{pet1, pet2});
Child child2 = new Child();
child2.setFirstName("Lisa");
@@ -74,7 +74,7 @@ public static Family getWakefieldFamilyItem() {
child2.setGrade(1);
child2.setGender("female");
- wakefieldFamily.setChildren(new Child[] { child1, child2 });
+ wakefieldFamily.setChildren(new Child[]{child1, child2});
Address address = new Address();
address.setCity("NY");
diff --git a/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java b/src/main/java/com/azure/cosmos/examples/crudquickstart/async/SampleCRUDQuickstartAsync.java
index 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