use of com.azure.cosmos.CosmosAsyncDatabase in project azure-cosmos-java-sql-api-samples by Azure-Samples.
the class SalesOrder method MigrateJavaSDKv4ResourceAsync.
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Migrate previous versions to Java SDK v4
*/
/**
* Migrate previous versions to Java SDK v4
*/
public static void MigrateJavaSDKv4ResourceAsync() {
String container_id = "family_container";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <MigrateJavaSDKv4ResourceAsync>
// Create Async client.
// Building an async client is still a sync operation.
CosmosAsyncClient client = new CosmosClientBuilder().endpoint("your.hostname").key("yourmasterkey").consistencyLevel(ConsistencyLevel.EVENTUAL).buildAsyncClient();
// Create database with specified name
client.createDatabaseIfNotExists("YourDatabaseName").flatMap(databaseResponse -> {
testDatabaseAsync = client.getDatabase("YourDatabaseName");
// Container properties - name and partition key
CosmosContainerProperties containerProperties = new CosmosContainerProperties("YourContainerName", "/id");
// Provision manual throughput
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
// Create container
return database.createContainerIfNotExists(containerProperties, throughputProperties);
}).flatMap(containerResponse -> {
testContainerAsync = database.getContainer("YourContainerName");
return Mono.empty();
}).subscribe();
// </MigrateJavaSDKv4ResourceAsync>
}
use of com.azure.cosmos.CosmosAsyncDatabase in project azure-cosmos-java-sql-api-samples by Azure-Samples.
the class SalesOrder method MigrateJavaSDKv4IndexingAsync.
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Indexing
*/
/**
* Indexing
*/
public static void MigrateJavaSDKv4IndexingAsync() {
String containerName = "family_container";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <MigrateIndexingAsync>
CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/lastName");
// Custom indexing policy
IndexingPolicy indexingPolicy = new IndexingPolicy();
indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT);
// Included paths
List<IncludedPath> includedPaths = new ArrayList<>();
includedPaths.add(new IncludedPath("/*"));
indexingPolicy.setIncludedPaths(includedPaths);
// Excluded paths
List<ExcludedPath> excludedPaths = new ArrayList<>();
excludedPaths.add(new ExcludedPath("/name/*"));
indexingPolicy.setExcludedPaths(excludedPaths);
containerProperties.setIndexingPolicy(indexingPolicy);
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
database.createContainerIfNotExists(containerProperties, throughputProperties);
CosmosAsyncContainer containerIfNotExists = database.getContainer(containerName);
// </MigrateIndexingAsync>
}
use of com.azure.cosmos.CosmosAsyncDatabase in project kafka-connect-cosmosdb by microsoft.
the class CosmosDBSourceTaskTest method setup.
@Before
// Need to maintain Typed objects
@SuppressWarnings("unchecked")
public void setup() throws IllegalAccessException {
testTask = new CosmosDBSourceTask();
// Configure settings
sourceSettings = CosmosDBSourceConfigTest.setupConfigs();
sourceSettings.put(CosmosDBSourceConfig.COSMOS_CONTAINER_TOPIC_MAP_CONF, topicName + "#" + containerName);
sourceSettings.put(CosmosDBSourceConfig.COSMOS_DATABASE_NAME_CONF, databaseName);
sourceSettings.put(CosmosDBSourceConfig.COSMOS_ASSIGNED_CONTAINER_CONF, containerName);
sourceSettings.put(CosmosDBSourceConfig.COSMOS_SOURCE_TASK_POLL_INTERVAL_CONF, "500");
sourceSettings.put(CosmosDBSourceConfig.COSMOS_SOURCE_TASK_BATCH_SIZE_CONF, "1");
sourceSettings.put(CosmosDBSourceConfig.COSMOS_SOURCE_TASK_BUFFER_SIZE_CONF, "5000");
sourceSettings.put(CosmosDBSourceConfig.COSMOS_SOURCE_TASK_TIMEOUT_CONF, "1000");
config = new CosmosDBSourceConfig(sourceSettings);
FieldUtils.writeField(testTask, "config", config, true);
// Create the TransferQueue
LinkedTransferQueue<JsonNode> queue = new LinkedTransferQueue<>();
FieldUtils.writeField(testTask, "queue", queue, true);
// Set the running flag to true
AtomicBoolean running = new AtomicBoolean();
running.set(true);
FieldUtils.writeField(testTask, "running", running, true);
// Mock the Cosmos SDK
mockCosmosClient = Mockito.mock(CosmosAsyncClient.class);
CosmosAsyncDatabase mockDatabase = Mockito.mock(CosmosAsyncDatabase.class);
when(mockCosmosClient.getDatabase(anyString())).thenReturn(mockDatabase);
mockFeedContainer = Mockito.mock(CosmosAsyncContainer.class);
when(mockDatabase.getContainer("feed")).thenReturn(mockFeedContainer);
mockLeaseContainer = Mockito.mock(CosmosAsyncContainer.class);
when(mockDatabase.getContainer("lease")).thenReturn(mockLeaseContainer);
// Mock query results and iterator for getting lease container token
CosmosPagedFlux<JsonNode> mockLeaseQueryResults = (CosmosPagedFlux<JsonNode>) Mockito.mock(CosmosPagedFlux.class);
when(mockLeaseContainer.queryItems(anyString(), any(), eq(JsonNode.class))).thenReturn(mockLeaseQueryResults);
Iterable<JsonNode> mockLeaseQueryIterable = (Iterable<JsonNode>) Mockito.mock(Iterable.class);
when(mockLeaseQueryResults.toIterable()).thenReturn(mockLeaseQueryIterable);
Iterator<JsonNode> mockLeaseQueryIterator = (Iterator<JsonNode>) Mockito.mock(Iterator.class);
when(mockLeaseQueryIterable.iterator()).thenReturn(mockLeaseQueryIterator);
when(mockLeaseQueryIterator.hasNext()).thenReturn(false);
FieldUtils.writeField(testTask, "client", mockCosmosClient, true);
FieldUtils.writeField(testTask, "leaseContainer", mockLeaseContainer, true);
}
use of com.azure.cosmos.CosmosAsyncDatabase in project azure-cosmos-java-sql-api-samples by Azure-Samples.
the class SampleChangeFeedProcessor method main.
public static void main(String[] args) {
logger.info("BEGIN Sample");
try {
// Summary of the next four commands:
// -Create an asynchronous Azure Cosmos DB client and database so that we can issue async requests to the DB
// -Create a "feed container" and a "lease container" in the DB
logger.info("-->CREATE DocumentClient");
CosmosAsyncClient client = getCosmosClient();
logger.info("-->CREATE sample's database: " + DATABASE_NAME);
CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME);
logger.info("-->CREATE container for documents: " + COLLECTION_NAME);
CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME);
logger.info("-->CREATE container for lease: " + COLLECTION_NAME + "-leases");
CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases");
// Model of a worker thread or application which leases access to monitor one or more feed container
// partitions via the Change Feed. In a real-world application you might deploy this code in an Azure function.
// The next line causes the worker to create and start an instance of the Change Feed Processor. See the implementation of getChangeFeedProcessor() for guidance
// on creating a handler for Change Feed events. In this stream, we also trigger the insertion of 10 documents on a separate
// thread.
logger.info("-->START Change Feed Processor on worker (handles changes asynchronously)");
changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer);
changeFeedProcessorInstance.start().subscribeOn(Schedulers.elastic()).doOnSuccess(aVoid -> {
// pass
}).subscribe();
// These two lines model an application which is inserting ten documents into the feed container
logger.info("-->START application that inserts documents into feed container");
createNewDocumentsCustomPOJO(feedContainer, 10, Duration.ofSeconds(3));
isWorkCompleted = true;
// This loop models the Worker main loop, which spins while its Change Feed Processor instance asynchronously
// handles incoming Change Feed events from the feed container. Of course in this sample, polling
// isWorkCompleted is unnecessary because items are being added to the feed container on the same thread, and you
// can see just above isWorkCompleted is set to true.
// But conceptually the worker is part of a different thread or application than the one which is inserting
// into the feed container; so this code illustrates the worker waiting and listening for changes to the feed container
long remainingWork = WAIT_FOR_WORK;
while (!isWorkCompleted && remainingWork > 0) {
Thread.sleep(100);
remainingWork -= 100;
}
// When all documents have been processed, clean up
if (isWorkCompleted) {
if (changeFeedProcessorInstance != null) {
changeFeedProcessorInstance.stop().subscribe();
}
} else {
throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time");
}
logger.info("-->DELETE sample's database: " + DATABASE_NAME);
deleteDatabase(cosmosDatabase);
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
logger.info("END Sample");
}
use of com.azure.cosmos.CosmosAsyncDatabase in project azure-cosmos-java-sql-api-samples by Azure-Samples.
the class SalesOrder method MigrateJavaSDKv4ContainerTTLAsync.
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Container TTL
*/
/**
* Container TTL
*/
public static void MigrateJavaSDKv4ContainerTTLAsync() {
String hostName = "hostname";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <MigrateContainerTTLAsync>
CosmosAsyncContainer container;
// Create a new container with TTL enabled with default expiration value
CosmosContainerProperties containerProperties = new CosmosContainerProperties("myContainer", "/myPartitionKey");
containerProperties.setDefaultTimeToLiveInSeconds(90 * 60 * 60 * 24);
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
database.createContainerIfNotExists(containerProperties, throughputProperties).block();
container = database.getContainer("myContainer");
// </MigrateContainerTTLAsync>
}
Aggregations