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

Commit ba4feb3

Browse files
committed
Add example source
1 parent b25e138 commit ba4feb3

28 files changed

Lines changed: 3934 additions & 0 deletions
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
package com.azure.cosmos.examples;
5+
6+
import org.apache.commons.lang3.StringUtils;
7+
8+
/**
9+
* Contains the account configurations for Sample.
10+
*
11+
* For running tests, you can pass a customized endpoint configuration in one of the following
12+
* ways:
13+
* <ul>
14+
* <li>-DACCOUNT_KEY="[your-key]" -DACCOUNT_HOST="[your-endpoint]" as JVM
15+
* command-line option.</li>
16+
* <li>You can set COSMOS_ACCOUNT_KEY and COSMOS_ACCOUNT_HOST as environment variables.</li>
17+
* </ul>
18+
*
19+
* If none of the above is set, emulator endpoint will be used.
20+
* Emulator http cert is self signed. If you are using emulator,
21+
* make sure emulator https certificate is imported
22+
* to java trusted cert store:
23+
* https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator-export-ssl-certificates
24+
*/
25+
public class AccountSettings {
26+
// REPLACE MASTER_KEY and HOST with values from your Azure Cosmos DB account.
27+
// The default values are credentials of the local emulator, which are not used in any production environment.
28+
public static final String HOST =
29+
System.getProperty("ACCOUNT_HOST",
30+
StringUtils.defaultString(StringUtils.trimToNull(
31+
System.getenv().get("COSMOS_ACCOUNT_HOST")),
32+
"https://localhost:8081/"));
33+
public static final String MASTER_KEY =
34+
System.getProperty("ACCOUNT_KEY",
35+
StringUtils.defaultString(StringUtils.trimToNull(
36+
System.getenv().get("COSMOS_ACCOUNT_KEY")),
37+
"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="));
38+
}
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
package com.azure.cosmos.examples;
4+
5+
import com.azure.cosmos.CosmosAsyncClient;
6+
import com.azure.cosmos.CosmosAsyncContainer;
7+
import com.azure.cosmos.CosmosAsyncDatabase;
8+
import com.azure.cosmos.CosmosAsyncItemResponse;
9+
import com.azure.cosmos.CosmosClientException;
10+
import com.azure.cosmos.CosmosContainerProperties;
11+
import com.azure.cosmos.CosmosContinuablePagedFlux;
12+
import com.azure.cosmos.implementation.CosmosItemProperties;
13+
import com.azure.cosmos.FeedOptions;
14+
import com.azure.cosmos.FeedResponse;
15+
import com.azure.cosmos.PartitionKey;
16+
import reactor.core.publisher.Mono;
17+
import reactor.core.scheduler.Schedulers;
18+
19+
public class BasicDemo {
20+
21+
private static final String DATABASE_NAME = "test_db";
22+
private static final String CONTAINER_NAME = "test_container";
23+
private CosmosAsyncClient client;
24+
private CosmosAsyncDatabase database;
25+
private CosmosAsyncContainer container;
26+
27+
public static void main(String[] args) {
28+
BasicDemo demo = new BasicDemo();
29+
demo.start();
30+
}
31+
32+
private void start() {
33+
// Get client
34+
client = CosmosAsyncClient.cosmosClientBuilder()
35+
.setEndpoint(AccountSettings.HOST)
36+
.setKey(AccountSettings.MASTER_KEY)
37+
.buildAsyncClient();
38+
39+
//CREATE a database and a container
40+
createDbAndContainerBlocking();
41+
42+
//Get a proxy reference to container
43+
container = client.getDatabase(DATABASE_NAME).getContainer(CONTAINER_NAME);
44+
45+
CosmosAsyncContainer container = client.getDatabase(DATABASE_NAME).getContainer(CONTAINER_NAME);
46+
TestObject testObject = new TestObject("item_new_id_1", "test", "test description", "US");
47+
TestObject testObject2 = new TestObject("item_new_id_2", "test2", "test description2", "CA");
48+
49+
//CREATE an Item async
50+
51+
Mono<CosmosAsyncItemResponse<TestObject>> itemResponseMono = container.createItem(testObject);
52+
//CREATE another Item async
53+
Mono<CosmosAsyncItemResponse<TestObject>> itemResponseMono1 = container.createItem(testObject2);
54+
55+
//Wait for completion
56+
try {
57+
itemResponseMono.doOnError(throwable -> log("CREATE item 1", throwable))
58+
.mergeWith(itemResponseMono1)
59+
.doOnError(throwable -> log("CREATE item 2 ", throwable))
60+
.doOnComplete(() -> log("Items created"))
61+
.publishOn(Schedulers.elastic())
62+
.blockLast();
63+
} catch (RuntimeException e) {
64+
log("Couldn't create items due to above exceptions");
65+
}
66+
67+
createAndReplaceItem();
68+
queryItems();
69+
queryWithContinuationToken();
70+
71+
//Close client
72+
client.close();
73+
log("Completed");
74+
}
75+
76+
private void createAndReplaceItem() {
77+
TestObject replaceObject = new TestObject("item_new_id_3", "test3", "test description3", "JP");
78+
TestObject properties = null;
79+
//CREATE item sync
80+
try {
81+
properties = container.createItem(replaceObject)
82+
.doOnError(throwable -> log("CREATE 3", throwable))
83+
.publishOn(Schedulers.elastic())
84+
.block()
85+
.getResource();
86+
} catch (RuntimeException e) {
87+
log("Couldn't create items due to above exceptions");
88+
}
89+
if (properties != null) {
90+
replaceObject.setName("new name test3");
91+
92+
//REPLACE the item and wait for completion
93+
container.replaceItem(replaceObject,
94+
properties.getId(),
95+
new PartitionKey(replaceObject.getCountry()))
96+
.block();
97+
}
98+
}
99+
100+
private void createDbAndContainerBlocking() {
101+
client.createDatabaseIfNotExists(DATABASE_NAME)
102+
.doOnSuccess(cosmosDatabaseResponse -> log("Database: " + cosmosDatabaseResponse.getDatabase().getId()))
103+
.flatMap(dbResponse -> dbResponse.getDatabase()
104+
.createContainerIfNotExists(new CosmosContainerProperties(CONTAINER_NAME,
105+
"/country")))
106+
.doOnSuccess(cosmosContainerResponse -> log("Container: " + cosmosContainerResponse.getContainer().getId()))
107+
.doOnError(throwable -> log(throwable.getMessage()))
108+
.publishOn(Schedulers.elastic())
109+
.block();
110+
}
111+
112+
private void queryItems() {
113+
log("+ Querying the collection ");
114+
String query = "SELECT * from root";
115+
FeedOptions options = new FeedOptions();
116+
options.setMaxDegreeOfParallelism(2);
117+
CosmosContinuablePagedFlux<TestObject> queryFlux = container.queryItems(query, options, TestObject.class);
118+
119+
queryFlux.byPage()
120+
.publishOn(Schedulers.elastic())
121+
.toIterable()
122+
.forEach(cosmosItemFeedResponse -> {
123+
log(cosmosItemFeedResponse.getResults());
124+
});
125+
126+
}
127+
128+
private void queryWithContinuationToken() {
129+
log("+ Query with paging using continuation token");
130+
String query = "SELECT * from root r ";
131+
FeedOptions options = new FeedOptions();
132+
options.populateQueryMetrics(true);
133+
options.maxItemCount(1);
134+
String continuation = null;
135+
do {
136+
options.requestContinuation(continuation);
137+
CosmosContinuablePagedFlux<TestObject> queryFlux = container.queryItems(query, options, TestObject.class);
138+
FeedResponse<TestObject> page = queryFlux.byPage().blockFirst();
139+
assert page != null;
140+
log(page.getResults());
141+
continuation = page.getContinuationToken();
142+
} while (continuation != null);
143+
144+
}
145+
146+
private void log(Object object) {
147+
System.out.println(object);
148+
}
149+
150+
private void log(String msg, Throwable throwable) {
151+
if (throwable instanceof CosmosClientException) {
152+
log(msg + ": " + ((CosmosClientException) throwable).getStatusCode());
153+
}
154+
}
155+
156+
static class TestObject {
157+
String id;
158+
String name;
159+
String description;
160+
String country;
161+
162+
public TestObject() {
163+
}
164+
165+
public TestObject(String id, String name, String description, String country) {
166+
this.id = id;
167+
this.name = name;
168+
this.description = description;
169+
this.country = country;
170+
}
171+
172+
public String getId() {
173+
return id;
174+
}
175+
176+
public void setId(String id) {
177+
this.id = id;
178+
}
179+
180+
public String getCountry() {
181+
return country;
182+
}
183+
184+
public void setCountry(String country) {
185+
this.country = country;
186+
}
187+
188+
public String getName() {
189+
return name;
190+
}
191+
192+
public void setName(String name) {
193+
this.name = name;
194+
}
195+
196+
public String getDescription() {
197+
return description;
198+
}
199+
200+
public void setDescription(String description) {
201+
this.description = description;
202+
}
203+
}
204+
}
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
package com.azure.cosmos.examples;
4+
5+
import com.azure.cosmos.CosmosAsyncClient;
6+
import com.azure.cosmos.CosmosAsyncContainer;
7+
import com.azure.cosmos.CosmosClientBuilder;
8+
import com.azure.cosmos.implementation.CosmosItemProperties;
9+
import com.azure.cosmos.PartitionKey;
10+
import reactor.core.publisher.Mono;
11+
12+
import java.io.IOException;
13+
14+
public class HelloWorldDemo {
15+
public static void main(String[] args) {
16+
new HelloWorldDemo().runDemo();
17+
}
18+
19+
void runDemo() {
20+
// Create a new CosmosAsyncClient via the CosmosClientBuilder
21+
// It only requires endpoint and key, but other useful settings are available
22+
CosmosAsyncClient client = new CosmosClientBuilder()
23+
.setEndpoint("<YOUR ENDPOINT HERE>")
24+
.setKey("<YOUR KEY HERE>")
25+
.buildAsyncClient();
26+
27+
// Get a reference to the container
28+
// This will create (or read) a database and its container.
29+
CosmosAsyncContainer container = client.createDatabaseIfNotExists("contoso-travel")
30+
// TIP: Our APIs are Reactor Core based, so try to chain your calls
31+
.flatMap(response -> response.getDatabase()
32+
.createContainerIfNotExists("passengers", "/id"))
33+
.flatMap(response -> Mono.just(response.getContainer()))
34+
.block(); // Blocking for demo purposes (avoid doing this in production unless you must)
35+
36+
// Create an item
37+
container.createItem(new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"))
38+
.flatMap(response -> {
39+
System.out.println("Created item: " + response.getResource());
40+
// Read that item 👓
41+
return container.readItem(response.getResource().getId(),
42+
new PartitionKey(response.getResource().getId()),
43+
Passenger.class);
44+
})
45+
.flatMap(response -> {
46+
System.out.println("Read item: " + response.getResource());
47+
// Replace that item 🔁
48+
Passenger p = response.getResource();
49+
p.setDestination("SFO");
50+
return container.replaceItem(p,
51+
response.getResource().getId(),
52+
new PartitionKey(response.getResource().getId()));
53+
})
54+
// delete that item 💣
55+
.flatMap(response -> container.deleteItem(response.getResource().getId(),
56+
new PartitionKey(response.getResource().getId())))
57+
.block(); // Blocking for demo purposes (avoid doing this in production unless you must)
58+
}
59+
60+
// Just a random object for demo's sake
61+
public class Passenger {
62+
String id;
63+
String name;
64+
String destination;
65+
String source;
66+
67+
public Passenger(String id, String name, String destination, String source) {
68+
this.id = id;
69+
this.name = name;
70+
this.destination = destination;
71+
this.source = source;
72+
}
73+
public String getId() {
74+
return id;
75+
}
76+
77+
public void setId(String id) {
78+
this.id = id;
79+
}
80+
81+
public String getName() {
82+
return name;
83+
}
84+
85+
public void setName(String name) {
86+
this.name = name;
87+
}
88+
89+
public String getDestination() {
90+
return destination;
91+
}
92+
93+
public void setDestination(String destination) {
94+
this.destination = destination;
95+
}
96+
97+
public String getSource() {
98+
return source;
99+
}
100+
101+
public void setSource(String source) {
102+
this.source = source;
103+
}
104+
}
105+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.azure.cosmos.examples.changefeed;
2+
3+
import com.azure.cosmos.JsonSerializable;
4+
5+
public class CustomPOJO {
6+
private String id;
7+
8+
public CustomPOJO() {
9+
10+
}
11+
12+
13+
public String getId() {
14+
return id;
15+
}
16+
17+
public void setId(String id) {
18+
this.id = id;
19+
}
20+
}

0 commit comments

Comments
 (0)