Skip to content
This repository was archived by the owner on Jul 13, 2026. It is now read-only.

Commit 96f49ec

Browse files
author
Theo van Kraay
committed
changes after further review
1 parent 784d2aa commit 96f49ec

4 files changed

Lines changed: 77 additions & 97 deletions

File tree

src/main/java/com/azure/cosmos/examples/containercrud/async/ContainerCRUDQuickstartAsync.java

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,9 @@ public static void main(String[] args) {
6060

6161
private void containerCRUDDemo() throws Exception {
6262

63-
logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
63+
logger.info("Using Azure Cosmos DB endpoint: {}", AccountSettings.HOST);
6464

65-
// Create sync client
65+
// Create async client
6666
client = new CosmosClientBuilder()
6767
.endpoint(AccountSettings.HOST)
6868
.key(AccountSettings.MASTER_KEY)
@@ -83,7 +83,7 @@ private void containerCRUDDemo() throws Exception {
8383

8484
// Database Create
8585
private void createDatabaseIfNotExists() throws Exception {
86-
logger.info("Create database " + databaseName + " if not exists...");
86+
logger.info("Create database {} if not exists...", databaseName);
8787

8888
// Create database if not exists
8989
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists(databaseName).block();
@@ -94,7 +94,7 @@ private void createDatabaseIfNotExists() throws Exception {
9494

9595
// Container create
9696
private void createContainerIfNotExists() throws Exception {
97-
logger.info("Create container " + containerName + " if not exists.");
97+
logger.info("Create container {} if not exists.", containerName);
9898

9999
// Create container if not exists
100100
CosmosContainerProperties containerProperties =
@@ -112,7 +112,7 @@ private void createContainerIfNotExists() throws Exception {
112112

113113
// Update container throughput
114114
private void updateContainerThroughput() throws Exception {
115-
logger.info("Update throughput for container " + containerName + ".");
115+
logger.info("Update throughput for container {}.", containerName);
116116

117117
// Specify new throughput value
118118
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(800);
@@ -123,7 +123,7 @@ private void updateContainerThroughput() throws Exception {
123123

124124
// Container read
125125
private void readContainerById() throws Exception {
126-
logger.info("Read container " + containerName + " by ID.");
126+
logger.info("Read container {} by ID.", containerName);
127127

128128
// Read container by ID
129129
container = database.getContainer(containerName);
@@ -133,7 +133,7 @@ private void readContainerById() throws Exception {
133133

134134
// Container read all
135135
private void readAllContainers() throws Exception {
136-
logger.info("Read all containers in database " + databaseName + ".");
136+
logger.info("Read all containers in database {}.", databaseName);
137137

138138
// Read all containers in the account
139139
CosmosPagedFlux<CosmosContainerProperties> containers = database.readAllContainers();
@@ -146,7 +146,7 @@ private void readAllContainers() throws Exception {
146146
+ " with request charge of " + readAllContainersResponse.getRequestCharge());
147147

148148
for (CosmosContainerProperties response : readAllContainersResponse.getResults()) {
149-
logger.info("container id: "+response.getId());
149+
logger.info("container id: {}", response.getId());
150150
//Got a page of query result with
151151
}
152152
return Flux.empty();
@@ -161,7 +161,7 @@ private void readAllContainers() throws Exception {
161161

162162
// Container delete
163163
private void deleteAContainer() throws Exception {
164-
logger.info("Delete container " + containerName + " by ID.");
164+
logger.info("Delete container {} by ID.", containerName);
165165

166166
// Delete container
167167
CosmosContainerResponse containerResp = database.getContainer(containerName).delete(new CosmosContainerRequestOptions()).block();
@@ -172,7 +172,7 @@ private void deleteAContainer() throws Exception {
172172

173173
// Database delete
174174
private void deleteADatabase() throws Exception {
175-
logger.info("Last step: delete database " + databaseName + " by ID.");
175+
logger.info("Last step: delete database {} by ID.", databaseName);
176176

177177
// Delete database
178178
CosmosDatabaseResponse dbResp = client.getDatabase(databaseName).delete(new CosmosDatabaseRequestOptions()).block();
@@ -184,7 +184,7 @@ private void deleteADatabase() throws Exception {
184184
// Multi-master only: Container create: last-writer-wins conflict resolution
185185
// Favor the newest write based on default (internal) timestamp
186186
private void createContainerIfNotExistsLWWDefaultTimestamp() throws Exception {
187-
logger.info("Create container " + containerName + " if not exists.");
187+
logger.info("Create container {} if not exists.", containerName);
188188

189189
// Create container properties structure
190190
CosmosContainerProperties containerProperties =
@@ -233,7 +233,7 @@ private void createContainerIfNotExistsLWWCustomTimestamp() throws Exception {
233233
// You will need to upload this stored procedure to the back-end using either
234234
// the stored procedure sample in this repo, or the Azure portal.
235235
private void createContainerIfNotExistsCustomSproc() throws Exception {
236-
logger.info("Create container " + containerName + " if not exists.");
236+
logger.info("Create container {} if not exists.", containerName);
237237

238238
// Create container properties structure
239239
CosmosContainerProperties containerProperties =
@@ -259,7 +259,7 @@ private void createContainerIfNotExistsCustomSproc() throws Exception {
259259
// This method will register the container as using conflict feed;
260260
// a separate method is needed to actually monitor the conflict feed.
261261
private void createContainerIfNotExistsCustomConflictFeed() throws Exception {
262-
logger.info("Create container " + containerName + " if not exists.");
262+
logger.info("Create container {} if not exists.", containerName);
263263

264264
// Create container properties structure
265265
CosmosContainerProperties containerProperties =

src/main/java/com/azure/cosmos/examples/databasecrud/async/DatabaseCRUDQuickstartAsync.java

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ private void databaseCRUDDemo() throws Exception {
6161

6262
logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
6363

64-
// Create sync client
64+
// Create async client
6565
client = new CosmosClientBuilder()
6666
.endpoint(AccountSettings.HOST)
6767
.key(AccountSettings.MASTER_KEY)
@@ -79,7 +79,7 @@ private void databaseCRUDDemo() throws Exception {
7979

8080
// Database Create
8181
private void createDatabaseIfNotExists() throws Exception {
82-
logger.info("Create database " + databaseName + " if not exists...");
82+
logger.info("Create database {} if not exists...", databaseName);
8383

8484
// Create database if not exists
8585
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists(databaseName).block();
@@ -90,7 +90,7 @@ private void createDatabaseIfNotExists() throws Exception {
9090

9191
// Database read
9292
private void readDatabaseById() throws Exception {
93-
logger.info("Read database " + databaseName + " by ID.");
93+
logger.info("Read database {} by ID.", databaseName);
9494

9595
// Read database by ID
9696
database = client.getDatabase(databaseName);
@@ -109,9 +109,7 @@ private void readAllDatabases() throws Exception {
109109
String msg="Listing databases in account:\n";
110110

111111
databases.byPage(100).flatMap(readAllDatabasesResponse -> {
112-
logger.info("read " +
113-
readAllDatabasesResponse.getResults().size() + " database(s)"
114-
+ " with request charge of " + readAllDatabasesResponse.getRequestCharge());
112+
logger.info("read {} database(s) with request charge of {}", readAllDatabasesResponse.getResults().size(),readAllDatabasesResponse.getRequestCharge());
115113

116114
for (CosmosDatabaseProperties response : readAllDatabasesResponse.getResults()) {
117115
logger.info("database id: "+response.getId());
@@ -127,7 +125,7 @@ private void readAllDatabases() throws Exception {
127125

128126
// Database delete
129127
private void deleteADatabase() throws Exception {
130-
logger.info("Last step: delete database " + databaseName + " by ID.");
128+
logger.info("Last step: delete database {} by ID.", databaseName);
131129

132130
// Delete database
133131
CosmosDatabaseResponse dbResp = client.getDatabase(databaseName).delete(new CosmosDatabaseRequestOptions()).block();

src/main/java/com/azure/cosmos/examples/documentcrud/async/DocumentCRUDQuickstartAsync.java

Lines changed: 57 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ public class DocumentCRUDQuickstartAsync {
5353
Family family = new Family();
5454
Family family2 = new Family();
5555

56+
List<Family> families = new ArrayList<>();
57+
5658
protected static Logger logger = LoggerFactory.getLogger(DocumentCRUDQuickstartAsync.class);
5759

5860
public void close() {
@@ -79,7 +81,7 @@ public static void main(String[] args) {
7981
logger.info("Demo complete, please hold while resources are released");
8082
} catch (Exception e) {
8183
e.printStackTrace();
82-
logger.error(String.format("Cosmos getStarted failed with %s", e));
84+
logger.error("Cosmos getStarted failed with {}", e);
8385
} finally {
8486
logger.info("Closing the client");
8587
p.shutdown();
@@ -103,7 +105,7 @@ private void documentCRUDDemo() throws Exception {
103105
createContainerIfNotExists();
104106

105107
//add docs to array
106-
List<Family> families = new ArrayList<>();
108+
107109
families.add(Families.getAndersenFamilyItem());
108110
families.add(Families.getWakefieldFamilyItem());
109111
families.add(Families.getJohnsonFamilyItem());
@@ -210,7 +212,7 @@ private void createDocument() throws Exception {
210212
}
211213

212214
private void createDocuments(Flux<Family> families) throws Exception {
213-
logger.info("Create documents {}", documentId);
215+
logger.info("Create documents {}", this.families.stream().map(x -> x.getId()).collect(Collectors.toList()));
214216

215217
// Define a document as a POJO (internally this
216218
// is converted to JSON via custom serialization)
@@ -220,10 +222,8 @@ private void createDocuments(Flux<Family> families) throws Exception {
220222
return container.createItem(family);
221223
}) // Flux of item request responses
222224
.flatMap(itemResponse -> {
223-
logger.info(String.format("Created item with request charge of %.2f within" +
224-
" duration %s",
225-
itemResponse.getRequestCharge(), itemResponse.getDuration()));
226-
logger.info(String.format("Item ID: %s\n", itemResponse.getItem().getId()));
225+
logger.info("Created item with request charge of {} within duration {}", itemResponse.getRequestCharge(), itemResponse.getDuration());
226+
logger.info("Item ID: {}\n", itemResponse.getItem().getId());
227227
return Mono.just(itemResponse.getRequestCharge());
228228
}) // Flux of request charges
229229
.reduce(0.0,
@@ -232,7 +232,7 @@ private void createDocuments(Flux<Family> families) throws Exception {
232232
.doOnSuccess(itemResponse -> {
233233
logger.info("Aggregated charge (all decimals): {}", itemResponse);
234234
// Preserve the total charge and print aggregate charge/item count stats.
235-
logger.info(String.format("Created items with total request charge of %.2f\n", itemResponse));
235+
logger.info("Created items with total request charge of {}\n", itemResponse);
236236
})
237237
.doOnError((exception) -> {
238238
logger.error(
@@ -366,45 +366,33 @@ private void upsertDocument() throws Exception {
366366
private void replaceDocumentWithConditionalEtagCheck() throws Exception {
367367
logger.info("Replace document {}, employing optimistic concurrency using ETag.", documentId);
368368

369-
// Obtained current document ETag
369+
//chain reading and replacing of item together in reactive stream
370370
container.readItem(documentId, new PartitionKey(documentLastName), Family.class)
371-
.doOnSuccess(itemResponse -> {
372-
logger.info("Request charge of readItem operation: {} RU", itemResponse.getRequestCharge());
373-
this.family = itemResponse.getItem();
374-
this.etag1 = itemResponse.getETag();
375-
})
376-
.doOnError((exception) -> {
377-
logger.error(
378-
"Exception 1. e: {}",
379-
exception.getLocalizedMessage(),
380-
exception);
381-
}).subscribe();
382-
383-
// We are adding Thread.sleep to mimic the some business computation that can
384-
// happen while waiting for earlier processes to finish.
385-
Thread.sleep(1000);
386-
387-
String etag = this.etag1;
388-
logger.info("Read document {} to obtain current ETag: {}", documentId, etag);
389-
390-
// Modify document
391-
Family family = this.family;
392-
family.setRegistered(!family.isRegistered());
393-
394-
// Persist the change back to the server, updating the ETag in the process
395-
// This models a concurrent change made to the document
396-
container.replaceItem(family, family.getId(), new PartitionKey(family.getLastName()), new CosmosItemRequestOptions())
397-
.doOnSuccess(itemResponse -> {
398-
logger.info("'Concurrent' update to document {} so ETag is now {}",documentId, itemResponse.getResponseHeaders().get("etag"));
399-
})
400-
.doOnError((exception) -> {
401-
logger.error(
402-
"Exception 2. e: {}",
403-
exception.getLocalizedMessage(),
404-
exception);
371+
.flatMap(response -> {
372+
logger.info("Read document {} to obtain current ETag: {}", documentId, response.getETag());
373+
//set instance variables for family nd etag1 to use later
374+
this.family = response.getItem();
375+
this.etag1 = response.getETag();
376+
logger.info("Request charge of readItem operation: {} RU", response.getRequestCharge());
377+
Family family = this.family;
378+
family.setRegistered(!family.isRegistered());
379+
// Persist the change back to the server, updating the ETag in the process
380+
// This models a concurrent change made to the document
381+
return container
382+
.replaceItem(family, family.getId(), new PartitionKey(family.getLastName()),
383+
new CosmosItemRequestOptions())
384+
.doOnSuccess(itemResponse -> {
385+
logger.info("'Concurrent' update to document {} so ETag is now {}", documentId,
386+
itemResponse.getResponseHeaders().get("etag"));
387+
})
388+
.doOnError((exception) -> {
389+
logger.error(
390+
"Exception e: {}",
391+
exception.getLocalizedMessage(),
392+
exception);
393+
});
405394
}).subscribe();
406395

407-
408396
// We are adding Thread.sleep to mimic the some business computation that can
409397
// happen while waiting for earlier processes to finish.
410398
Thread.sleep(1000);
@@ -413,7 +401,8 @@ private void replaceDocumentWithConditionalEtagCheck() throws Exception {
413401
// This should fail because the "concurrent" document change updated the ETag.
414402

415403
CosmosItemRequestOptions requestOptions = new CosmosItemRequestOptions();
416-
requestOptions.setIfMatchETag(etag);
404+
//using etag1 instance variable saved from earlier update to etag
405+
requestOptions.setIfMatchETag(this.etag1.toString());
417406

418407
family.setDistrict("Seafood");
419408

@@ -454,39 +443,32 @@ private void readDocumentOnlyIfChanged() throws Exception {
454443
String etag = this.etag2;
455444

456445
// Re-read doc but with conditional access requirement that ETag has changed.
457-
// This should fail.
446+
// This should fail (304).
458447
CosmosItemRequestOptions requestOptions = new CosmosItemRequestOptions();
459448
requestOptions.setIfNoneMatchETag(etag);
460449

461-
container
462-
.readItem(documentId, new PartitionKey(documentLastName), requestOptions, Family.class)
463-
.doOnSuccess(itemResponse -> {
464-
logger.info("Re-read doc with status code of {} (we anticipate failure due to ETag not having changed.)", itemResponse.getStatusCode());
465-
})
466-
.doOnError((exception) -> {
467-
logger.info("Exception. e: {}");
468-
})
469-
.onErrorResume(exception -> Mono.empty())
470-
.subscribe();
471-
472-
// We are adding Thread.sleep to mimic the some business computation that can
473-
// happen while waiting for earlier processes to finish.
474-
Thread.sleep(1000);
475-
476-
// Replace the doc with a modified version, which will update ETag
477-
Family family = this.family2;
478-
family.setRegistered(!family.isRegistered());
479-
container.replaceItem(family, family.getId(), new PartitionKey(family.getLastName()), new CosmosItemRequestOptions())
480-
.doOnSuccess(itemResponse -> {
481-
logger.info("Request charge of replace operation: {} RU", itemResponse.getRequestCharge());
482-
logger.info("Modified and replaced the doc (updates ETag.)");
483-
})
484-
.doOnError((exception) -> {
485-
logger.error(
486-
"Exception. e: {}",
487-
exception.getLocalizedMessage(),
488-
exception);
489-
}).subscribe();
450+
//chain reading and replacing of item together in reactive stream
451+
container.readItem(documentId, new PartitionKey(documentLastName), requestOptions, Family.class)
452+
.flatMap(response -> {
453+
logger.info("Re-read doc with status code of {} (we anticipate 304 failure due to ETag not having changed.)", response.getStatusCode());
454+
logger.info("Request charge of readItem operation: {} RU", response.getRequestCharge());
455+
Family family = this.family2;
456+
family.setRegistered(!family.isRegistered());
457+
// Replace the doc with a modified version, which will update ETag
458+
return container
459+
.replaceItem(family, family.getId(), new PartitionKey(family.getLastName()),
460+
new CosmosItemRequestOptions())
461+
.doOnSuccess(itemResponse -> {
462+
logger.info("'Concurrent' update to document {} so ETag is now {}", documentId,
463+
itemResponse.getResponseHeaders().get("etag"));
464+
})
465+
.doOnError((exception) -> {
466+
logger.error(
467+
"Exception e: {}",
468+
exception.getLocalizedMessage(),
469+
exception);
470+
});
471+
}).subscribe();
490472

491473
// We are adding Thread.sleep to mimic the some business computation that can
492474
// happen while waiting for earlier processes to finish.

src/main/java/com/azure/cosmos/examples/queries/async/QueriesQuickstartAsync.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ private void queriesDemo() throws Exception {
9595

9696
logger.info("Using Azure Cosmos DB endpoint: {}", AccountSettings.HOST);
9797

98-
// Create sync client
98+
// Create async client
9999
client = new CosmosClientBuilder()
100100
.endpoint(AccountSettings.HOST)
101101
.key(AccountSettings.MASTER_KEY)
@@ -459,7 +459,7 @@ private void deleteADocument() throws Exception {
459459
logger.info("Delete document {} by ID.", documentId);
460460

461461
// Delete document
462-
container.deleteItem(documentId, new PartitionKey(documentLastName), new CosmosItemRequestOptions());
462+
container.deleteItem(documentId, new PartitionKey(documentLastName), new CosmosItemRequestOptions()).block();
463463

464464
logger.info("Done.");
465465
}

0 commit comments

Comments
 (0)