Search in sources :

Example 6 with CosmosStoredProcedureRequestOptions

use of com.azure.cosmos.models.CosmosStoredProcedureRequestOptions in project DataSpaceConnector by eclipse-dataspaceconnector.

the class CosmosTransferProcessStoreIntegrationTest method invokeStoredProcedure.

@Test
void invokeStoredProcedure() {
    // create one item
    var tp = createTransferProcess("proc1");
    store.create(tp);
    List<Object> procedureParams = Arrays.asList(100, 5, connectorId);
    CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions();
    options.setPartitionKey(PartitionKey.NONE);
    CosmosStoredProcedureResponse sprocResponse = container.getScripts().getStoredProcedure("nextForState").execute(procedureParams, options);
    var result = sprocResponse.getResponseAsString();
    var l = typeManager.readValue(result, List.class);
    List<TransferProcessDocument> documents = (List<TransferProcessDocument>) l.stream().map(o -> typeManager.writeValueAsString(o)).map(json -> typeManager.readValue(json.toString(), TransferProcessDocument.class)).collect(Collectors.toList());
    assertThat(documents).allSatisfy(document -> {
        assertThat(document.getLease()).isNotNull().hasFieldOrPropertyWithValue("leasedBy", connectorId).hasFieldOrProperty("leasedAt");
    });
}
Also used : SortOrder(org.eclipse.dataspaceconnector.spi.query.SortOrder) IntStream(java.util.stream.IntStream) BadRequestException(com.azure.cosmos.implementation.BadRequestException) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) CosmosTestClient(org.eclipse.dataspaceconnector.azure.testfixtures.CosmosTestClient) TypeManager(org.eclipse.dataspaceconnector.spi.types.TypeManager) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) CosmosDatabase(com.azure.cosmos.CosmosDatabase) PartitionKey(com.azure.cosmos.models.PartitionKey) TransferProcess(org.eclipse.dataspaceconnector.spi.types.domain.transfer.TransferProcess) TestHelper.createTransferProcess(org.eclipse.dataspaceconnector.transfer.store.cosmos.TestHelper.createTransferProcess) AfterAll(org.junit.jupiter.api.AfterAll) CosmosStoredProcedureRequestOptions(com.azure.cosmos.models.CosmosStoredProcedureRequestOptions) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) AzureCosmosDbIntegrationTest(org.eclipse.dataspaceconnector.azure.testfixtures.annotations.AzureCosmosDbIntegrationTest) CosmosDbApiImpl(org.eclipse.dataspaceconnector.azure.cosmos.CosmosDbApiImpl) ResourceManifest(org.eclipse.dataspaceconnector.spi.types.domain.transfer.ResourceManifest) Awaitility.await(org.awaitility.Awaitility.await) DataRequest(org.eclipse.dataspaceconnector.spi.types.domain.transfer.DataRequest) RetryPolicy(net.jodah.failsafe.RetryPolicy) EdcException(org.eclipse.dataspaceconnector.spi.EdcException) CosmosStoredProcedureResponse(com.azure.cosmos.models.CosmosStoredProcedureResponse) UUID(java.util.UUID) CosmosItemResponse(com.azure.cosmos.models.CosmosItemResponse) TransferProcessDocument(org.eclipse.dataspaceconnector.transfer.store.cosmos.model.TransferProcessDocument) Collectors(java.util.stream.Collectors) QuerySpec(org.eclipse.dataspaceconnector.spi.query.QuerySpec) DisplayName(org.junit.jupiter.api.DisplayName) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) List(java.util.List) TestHelper.createTransferProcessDocument(org.eclipse.dataspaceconnector.transfer.store.cosmos.TestHelper.createTransferProcessDocument) ChronoUnit(java.time.temporal.ChronoUnit) CosmosPagedIterable(com.azure.cosmos.util.CosmosPagedIterable) CosmosContainer(com.azure.cosmos.CosmosContainer) TransferProcessStates(org.eclipse.dataspaceconnector.spi.types.domain.transfer.TransferProcessStates) Comparator(java.util.Comparator) CosmosStoredProcedureRequestOptions(com.azure.cosmos.models.CosmosStoredProcedureRequestOptions) TransferProcessDocument(org.eclipse.dataspaceconnector.transfer.store.cosmos.model.TransferProcessDocument) TestHelper.createTransferProcessDocument(org.eclipse.dataspaceconnector.transfer.store.cosmos.TestHelper.createTransferProcessDocument) List(java.util.List) CosmosStoredProcedureResponse(com.azure.cosmos.models.CosmosStoredProcedureResponse) AzureCosmosDbIntegrationTest(org.eclipse.dataspaceconnector.azure.testfixtures.annotations.AzureCosmosDbIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 7 with CosmosStoredProcedureRequestOptions

use of com.azure.cosmos.models.CosmosStoredProcedureRequestOptions 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)

Example 8 with CosmosStoredProcedureRequestOptions

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

the class SampleStoredProcedure method executeStoredProcedureArrayArg.

public void executeStoredProcedureArrayArg() throws Exception {
    logger.info(String.format("Executing stored procedure %s...\n\n", sprocId + "ArrayArg"));
    String partitionValue = "Seattle";
    CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions();
    options.setPartitionKey(new PartitionKey(partitionValue));
    List<Object> pojos = new ArrayList<>();
    pojos.add(new CustomPOJO("idA", partitionValue));
    pojos.add(new CustomPOJO("idB", partitionValue));
    pojos.add(new CustomPOJO("idC", partitionValue));
    List<Object> sproc_args = new ArrayList<>();
    sproc_args.add(OBJECT_MAPPER.writeValueAsString(pojos));
    CosmosStoredProcedureResponse executeResponse = container.getScripts().getStoredProcedure(sprocId + "ArrayArg").execute(sproc_args, options);
    logger.info(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", sprocId + "ArrayArg", executeResponse.getResponseAsString(), executeResponse.getStatusCode(), executeResponse.getRequestCharge()));
}
Also used : CosmosStoredProcedureRequestOptions(com.azure.cosmos.models.CosmosStoredProcedureRequestOptions) ArrayList(java.util.ArrayList) PartitionKey(com.azure.cosmos.models.PartitionKey) CosmosStoredProcedureResponse(com.azure.cosmos.models.CosmosStoredProcedureResponse) CustomPOJO(com.azure.cosmos.examples.common.CustomPOJO)

Example 9 with CosmosStoredProcedureRequestOptions

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

the class SampleStoredProcedure method executeStoredProcedure.

public void executeStoredProcedure() throws Exception {
    logger.info(String.format("Executing stored procedure %s...\n\n", sprocId));
    CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions();
    options.setPartitionKey(new PartitionKey("Seattle"));
    CosmosStoredProcedureResponse executeResponse = container.getScripts().getStoredProcedure(sprocId).execute(null, options);
    logger.info(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n", sprocId, executeResponse.getResponseAsString(), executeResponse.getStatusCode(), executeResponse.getRequestCharge()));
}
Also used : CosmosStoredProcedureRequestOptions(com.azure.cosmos.models.CosmosStoredProcedureRequestOptions) PartitionKey(com.azure.cosmos.models.PartitionKey) CosmosStoredProcedureResponse(com.azure.cosmos.models.CosmosStoredProcedureResponse)

Example 10 with CosmosStoredProcedureRequestOptions

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

the class SampleStoredProcedure method createStoredProcedureArrayArg.

public void createStoredProcedureArrayArg() throws Exception {
    logger.info("Creating stored procedure...");
    sprocId = "createMyDocument";
    String sprocBody = "function " + sprocId + "ArrayArg(jsonArray) {\n" + "    var context = getContext();\n" + "    var container = context.getCollection();\n" + "    //validate if input is valid json\n" + "    if (typeof jsonArray === \"string\") {\n" + "       try {\n" + "            jsonArray = JSON.parse(jsonArray);\n" + "        } catch (e) {\n" + "            throw \"Bad input to store procedure should be array of json string.\";\n" + "        }\n" + "    } else {\n" + "        throw \"Bad input to store procedure should be array of json string.\";\n" + "    }\n" + "    var resultDocuments = [];\n" + "    jsonArray.forEach(function(jsonDoc) {\n" + "        if (jsonDoc.isUpdate != undefined && jsonDoc.isUpdate === true) {\n" + "            var accepted = container.replaceDocument(jsonDoc._self, jsonDoc, { etag: jsonDoc._etag },\n" + "            function (err, docReplaced) {\n" + "                if (err) throw new Error('Error' + err.message);\n" + "                resultDocuments.push(docReplaced);\n" + "            });\n" + "            if (!accepted) throw \"Unable to update document, abort \";\n" + "        } else {\n" + "            var accepted = container.createDocument(container.getSelfLink(), jsonDoc,\n" + "                    function (err, itemCreated) {\n" + "                if (err) throw new Error('Error' + err.message);\n" + "                resultDocuments.push(itemCreated);\n" + "            });\n" + "            if (!accepted) throw \"Unable to create document, abort \";\n" + "        }\n" + "    });\n" + "    context.getResponse().setBody(resultDocuments);\n" + "}\n";
    CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId + "ArrayArg", sprocBody);
    container.getScripts().createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions());
}
Also used : CosmosStoredProcedureRequestOptions(com.azure.cosmos.models.CosmosStoredProcedureRequestOptions) CosmosStoredProcedureProperties(com.azure.cosmos.models.CosmosStoredProcedureProperties)

Aggregations

CosmosStoredProcedureRequestOptions (com.azure.cosmos.models.CosmosStoredProcedureRequestOptions)10 PartitionKey (com.azure.cosmos.models.PartitionKey)7 CosmosStoredProcedureProperties (com.azure.cosmos.models.CosmosStoredProcedureProperties)6 CosmosStoredProcedureResponse (com.azure.cosmos.models.CosmosStoredProcedureResponse)5 CosmosItemResponse (com.azure.cosmos.models.CosmosItemResponse)4 List (java.util.List)3 ConsistencyLevel (com.azure.cosmos.ConsistencyLevel)2 CosmosAsyncClient (com.azure.cosmos.CosmosAsyncClient)2 CosmosAsyncContainer (com.azure.cosmos.CosmosAsyncContainer)2 CosmosAsyncDatabase (com.azure.cosmos.CosmosAsyncDatabase)2 CosmosClientBuilder (com.azure.cosmos.CosmosClientBuilder)2 CosmosContainer (com.azure.cosmos.CosmosContainer)2 CosmosDatabase (com.azure.cosmos.CosmosDatabase)2 CustomPOJO (com.azure.cosmos.examples.common.CustomPOJO)2 BadRequestException (com.azure.cosmos.implementation.BadRequestException)2 CosmosPagedIterable (com.azure.cosmos.util.CosmosPagedIterable)2 ChronoUnit (java.time.temporal.ChronoUnit)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 UUID (java.util.UUID)2