Search in sources :

Example 6 with CosmosAsyncContainer

use of com.azure.cosmos.CosmosAsyncContainer in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class SalesOrder method ManageConsistencyLevelsInAzureCosmosDBSessionTokenAsync.

/**
 * https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-manage-consistency
 * Utilize session tokens
 */
/**
 * Session token
 */
public static void ManageConsistencyLevelsInAzureCosmosDBSessionTokenAsync() {
    String itemId = "Henderson";
    String partitionKey = "4A3B-6Y78";
    CosmosAsyncContainer container = null;
    // <ManageConsistencySessionAsync>
    // Get session token from response
    CosmosItemResponse<JsonNode> response = container.readItem(itemId, new PartitionKey(partitionKey), JsonNode.class).block();
    String sessionToken = response.getSessionToken();
    // Resume the session by setting the session token on the RequestOptions
    CosmosItemRequestOptions options = new CosmosItemRequestOptions();
    options.setSessionToken(sessionToken);
    CosmosItemResponse<JsonNode> response2 = container.readItem(itemId, new PartitionKey(partitionKey), JsonNode.class).block();
// </ManageConsistencySessionAsync>
}
Also used : CosmosItemRequestOptions(com.azure.cosmos.models.CosmosItemRequestOptions) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) PartitionKey(com.azure.cosmos.models.PartitionKey) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Example 7 with CosmosAsyncContainer

use of com.azure.cosmos.CosmosAsyncContainer 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>
}
Also used : ThroughputProperties(com.azure.cosmos.models.ThroughputProperties) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) CosmosAsyncDatabase(com.azure.cosmos.CosmosAsyncDatabase) CosmosContainerProperties(com.azure.cosmos.models.CosmosContainerProperties) ArrayList(java.util.ArrayList) IncludedPath(com.azure.cosmos.models.IncludedPath) ExcludedPath(com.azure.cosmos.models.ExcludedPath) IndexingPolicy(com.azure.cosmos.models.IndexingPolicy)

Example 8 with CosmosAsyncContainer

use of com.azure.cosmos.CosmosAsyncContainer 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");
}
Also used : ChangeFeedProcessorBuilder(com.azure.cosmos.ChangeFeedProcessorBuilder) CosmosContainerProperties(com.azure.cosmos.models.CosmosContainerProperties) Logger(org.slf4j.Logger) Utils(com.azure.cosmos.implementation.Utils) CosmosContainerResponse(com.azure.cosmos.models.CosmosContainerResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) RandomStringUtils(com.azure.cosmos.implementation.apachecommons.lang.RandomStringUtils) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ChangeFeedProcessor(com.azure.cosmos.ChangeFeedProcessor) CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) CosmosContainerRequestOptions(com.azure.cosmos.models.CosmosContainerRequestOptions) List(java.util.List) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) CosmosAsyncDatabase(com.azure.cosmos.CosmosAsyncDatabase) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) CosmosDatabaseResponse(com.azure.cosmos.models.CosmosDatabaseResponse) ThroughputProperties(com.azure.cosmos.models.ThroughputProperties) CustomPOJO2(com.azure.cosmos.examples.common.CustomPOJO2) Duration(java.time.Duration) Schedulers(reactor.core.scheduler.Schedulers) ConsistencyLevel(com.azure.cosmos.ConsistencyLevel) CosmosException(com.azure.cosmos.CosmosException) JsonNode(com.fasterxml.jackson.databind.JsonNode) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) CosmosAsyncDatabase(com.azure.cosmos.CosmosAsyncDatabase) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) CosmosException(com.azure.cosmos.CosmosException)

Example 9 with CosmosAsyncContainer

use of com.azure.cosmos.CosmosAsyncContainer in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class SalesOrder method TroubleshootingGuideJavaSDKv4CustomSchedulerAsync.

/**
 * https://docs.microsoft.com/en-us/azure/cosmos-db/troubleshoot-java-sdk-v4-sql
 * Troubleshooting guide - custom scheduler
 * Async only
 */
/**
 * Troubleshooting guide - custom scheduler
 */
public static void TroubleshootingGuideJavaSDKv4CustomSchedulerAsync() {
    CosmosAsyncContainer container = null;
    CustomPOJO item = null;
    // <TroubleshootCustomSchedulerAsync>
    // Have a singleton instance of an executor and a scheduler.
    ExecutorService ex = Executors.newFixedThreadPool(30);
    Scheduler customScheduler = Schedulers.fromExecutor(ex);
// </TroubleshootCustomSchedulerAsync>
}
Also used : CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) Scheduler(reactor.core.scheduler.Scheduler) ExecutorService(java.util.concurrent.ExecutorService) CustomPOJO(com.azure.cosmos.examples.common.CustomPOJO)

Example 10 with CosmosAsyncContainer

use of com.azure.cosmos.CosmosAsyncContainer in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class SalesOrder method MigrateJavaSDKv4SprocAsync.

/**
 * https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
 * Stored procedure
 */
/**
 * Stored procedure
 */
public static void MigrateJavaSDKv4SprocAsync() {
    String containerName = "family_container";
    String partition_key = "/pk";
    CosmosAsyncContainer container = null;
    // <MigrateSprocAsync>
    logger.info("Creating stored procedure...\n");
    String 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);
    container.getScripts().createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block();
    // ...
    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 -> {
        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();
// </MigrateSprocAsync>
}
Also used : PartitionKey(com.azure.cosmos.models.PartitionKey) LoggerFactory(org.slf4j.LoggerFactory) ExcludedPath(com.azure.cosmos.models.ExcludedPath) Scheduler(reactor.core.scheduler.Scheduler) ArrayList(java.util.ArrayList) ProxyOptions(com.azure.core.http.ProxyOptions) DirectConnectionConfig(com.azure.cosmos.DirectConnectionConfig) Families(com.azure.cosmos.examples.common.Families) Family(com.azure.cosmos.examples.common.Family) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) CosmosStoredProcedureRequestOptions(com.azure.cosmos.models.CosmosStoredProcedureRequestOptions) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ThroughputProperties(com.azure.cosmos.models.ThroughputProperties) Duration(java.time.Duration) Schedulers(reactor.core.scheduler.Schedulers) ConsistencyLevel(com.azure.cosmos.ConsistencyLevel) JsonNode(com.fasterxml.jackson.databind.JsonNode) CosmosItemRequestOptions(com.azure.cosmos.models.CosmosItemRequestOptions) ExecutorService(java.util.concurrent.ExecutorService) ChangeFeedProcessorBuilder(com.azure.cosmos.ChangeFeedProcessorBuilder) CustomPOJO(com.azure.cosmos.examples.common.CustomPOJO) CosmosContainerProperties(com.azure.cosmos.models.CosmosContainerProperties) CosmosStoredProcedureProperties(com.azure.cosmos.models.CosmosStoredProcedureProperties) IndexingPolicy(com.azure.cosmos.models.IndexingPolicy) Logger(org.slf4j.Logger) GatewayConnectionConfig(com.azure.cosmos.GatewayConnectionConfig) IncludedPath(com.azure.cosmos.models.IncludedPath) IndexingMode(com.azure.cosmos.models.IndexingMode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Mono(reactor.core.publisher.Mono) ChangeFeedProcessor(com.azure.cosmos.ChangeFeedProcessor) CosmosItemResponse(com.azure.cosmos.models.CosmosItemResponse) CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Flux(reactor.core.publisher.Flux) List(java.util.List) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) CosmosAsyncDatabase(com.azure.cosmos.CosmosAsyncDatabase) ConflictResolutionPolicy(com.azure.cosmos.models.ConflictResolutionPolicy) CosmosStoredProcedureRequestOptions(com.azure.cosmos.models.CosmosStoredProcedureRequestOptions) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) PartitionKey(com.azure.cosmos.models.PartitionKey) CosmosStoredProcedureProperties(com.azure.cosmos.models.CosmosStoredProcedureProperties)

Aggregations

CosmosAsyncContainer (com.azure.cosmos.CosmosAsyncContainer)16 CustomPOJO (com.azure.cosmos.examples.common.CustomPOJO)9 CosmosAsyncDatabase (com.azure.cosmos.CosmosAsyncDatabase)7 CosmosContainerProperties (com.azure.cosmos.models.CosmosContainerProperties)7 ThroughputProperties (com.azure.cosmos.models.ThroughputProperties)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 ChangeFeedProcessor (com.azure.cosmos.ChangeFeedProcessor)4 ChangeFeedProcessorBuilder (com.azure.cosmos.ChangeFeedProcessorBuilder)4 CosmosItemRequestOptions (com.azure.cosmos.models.CosmosItemRequestOptions)4 CosmosItemResponse (com.azure.cosmos.models.CosmosItemResponse)4 PartitionKey (com.azure.cosmos.models.PartitionKey)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 Scheduler (reactor.core.scheduler.Scheduler)4 ConsistencyLevel (com.azure.cosmos.ConsistencyLevel)3 CosmosAsyncClient (com.azure.cosmos.CosmosAsyncClient)3 CosmosClientBuilder (com.azure.cosmos.CosmosClientBuilder)3 Family (com.azure.cosmos.examples.common.Family)3 ExcludedPath (com.azure.cosmos.models.ExcludedPath)3 IncludedPath (com.azure.cosmos.models.IncludedPath)3 IndexingPolicy (com.azure.cosmos.models.IndexingPolicy)3