Search in sources :

Example 6 with CosmosStoredProcedureProperties

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

the class CosmosContractNegotiationStoreIntegrationTest method uploadStoredProcedure.

private void uploadStoredProcedure(CosmosContainer container, String name) {
    var sprocName = ".js";
    var is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name + sprocName);
    if (is == null) {
        throw new AssertionError("The input stream referring to the " + name + " file cannot be null!");
    }
    var s = new Scanner(is).useDelimiter("\\A");
    if (!s.hasNext()) {
        throw new IllegalArgumentException("Error loading resource with name " + sprocName);
    }
    var body = s.next();
    var props = new CosmosStoredProcedureProperties(name, body);
    var scripts = container.getScripts();
    if (scripts.readAllStoredProcedures().stream().noneMatch(sp -> sp.getId().equals(name))) {
        scripts.createStoredProcedure(props);
    }
}
Also used : Scanner(java.util.Scanner) CosmosStoredProcedureProperties(com.azure.cosmos.models.CosmosStoredProcedureProperties)

Example 7 with CosmosStoredProcedureProperties

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

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

Example 9 with CosmosStoredProcedureProperties

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

the class SampleStoredProcedure method readAllSprocs.

private void readAllSprocs() throws Exception {
    logger.info("Listing all stored procedures associated with container " + containerName + "\n");
    CosmosPagedIterable<CosmosStoredProcedureProperties> feedResponseIterable = container.getScripts().readAllStoredProcedures();
    Iterator<CosmosStoredProcedureProperties> feedResponseIterator = feedResponseIterable.iterator();
    while (feedResponseIterator.hasNext()) {
        CosmosStoredProcedureProperties storedProcedureProperties = feedResponseIterator.next();
        logger.info(String.format("Stored Procedure: %s", storedProcedureProperties));
    }
}
Also used : CosmosStoredProcedureProperties(com.azure.cosmos.models.CosmosStoredProcedureProperties)

Example 10 with CosmosStoredProcedureProperties

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

the class CosmosTransferProcessStoreIntegrationTest method uploadStoredProcedure.

private static void uploadStoredProcedure(CosmosContainer container, String name) {
    var is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name + ".js");
    if (is == null) {
        throw new AssertionError("The input stream referring to the " + name + " file cannot be null!");
    }
    Scanner s = new Scanner(is).useDelimiter("\\A");
    String body = s.hasNext() ? s.next() : "";
    CosmosStoredProcedureProperties props = new CosmosStoredProcedureProperties(name, body);
    CosmosScripts scripts = container.getScripts();
    if (scripts.readAllStoredProcedures().stream().noneMatch(sp -> sp.getId().equals(name))) {
        CosmosStoredProcedureResponse storedProcedure = scripts.createStoredProcedure(props);
    }
}
Also used : Scanner(java.util.Scanner) CosmosStoredProcedureProperties(com.azure.cosmos.models.CosmosStoredProcedureProperties) CosmosStoredProcedureResponse(com.azure.cosmos.models.CosmosStoredProcedureResponse) CosmosScripts(com.azure.cosmos.CosmosScripts)

Aggregations

CosmosStoredProcedureProperties (com.azure.cosmos.models.CosmosStoredProcedureProperties)10 CosmosStoredProcedureRequestOptions (com.azure.cosmos.models.CosmosStoredProcedureRequestOptions)5 CosmosContainerProperties (com.azure.cosmos.models.CosmosContainerProperties)3 Scanner (java.util.Scanner)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 CustomPOJO (com.azure.cosmos.examples.common.CustomPOJO)2 CosmosItemResponse (com.azure.cosmos.models.CosmosItemResponse)2 PartitionKey (com.azure.cosmos.models.PartitionKey)2 ThroughputProperties (com.azure.cosmos.models.ThroughputProperties)2 ArrayList (java.util.ArrayList)2 Logger (org.slf4j.Logger)2 ProxyOptions (com.azure.core.http.ProxyOptions)1 ChangeFeedProcessor (com.azure.cosmos.ChangeFeedProcessor)1 ChangeFeedProcessorBuilder (com.azure.cosmos.ChangeFeedProcessorBuilder)1 CosmosDatabase (com.azure.cosmos.CosmosDatabase)1 CosmosException (com.azure.cosmos.CosmosException)1