comment
stringlengths
1
45k
method_body
stringlengths
23
281k
target_code
stringlengths
0
5.16k
method_body_after
stringlengths
12
281k
context_before
stringlengths
8
543k
context_after
stringlengths
8
543k
At least for JsonPatchOperation we need to differentiate between non-existent value and null value, in most other cases this shouldn't be needed.
public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); }
if (value.isInitialized()) {
public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override public String toString() { return toJson(new StringBuilder()).toString(); } @Override public StringBuilder toJson(StringBuilder stringBuilder) { stringBuilder.append("{\"op\":\"") .append(op.toString()) .append("\""); if (from != null) { stringBuilder.append(",\"from\":\"") .append(from) .append("\""); } stringBuilder.append(",\"path\":\"") .append(path) .append("\""); if (value.isInitialized()) { stringBuilder.append(",\"value\":") .append(value.getValue()); } return stringBuilder.append("}"); } @Override /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.deserializeObject(jsonReader, (reader, token) -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); token = jsonReader.nextToken(); switch (fieldName) { case "op": op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); break; case "from": from = jsonReader.getStringValue(); break; case "path": path = jsonReader.getStringValue(); break; case "value": if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { value = Option.of(jsonReader.readChildren()); } else if (token == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } break; default: break; } } return new JsonPatchOperation(op, from, path, value); }); } }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override public String toString() { return toJson(new StringBuilder()).toString(); } @Override public StringBuilder toJson(StringBuilder stringBuilder) { stringBuilder.append("{\"op\":\"") .append(op.toString()) .append("\""); if (from != null) { stringBuilder.append(",\"from\":\"") .append(from) .append("\""); } stringBuilder.append(",\"path\":\"") .append(path) .append("\""); if (value.isInitialized()) { stringBuilder.append(",\"value\":") .append(value.getValue()); } return stringBuilder.append("}"); } @Override /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.deserializeObject(jsonReader, (reader, token) -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); token = jsonReader.nextToken(); switch (fieldName) { case "op": op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); break; case "from": from = jsonReader.getStringValue(); break; case "path": path = jsonReader.getStringValue(); break; case "value": if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { value = Option.of(jsonReader.readChildren()); } else if (token == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } break; default: break; } } return new JsonPatchOperation(op, from, path, value); }); } }
will there be readme.md file? pls help to add more specific description on uasge of user token. keyvault, mysql flexible, network feature
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = (context, next) -> { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(profile.getEnvironment().getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); }; AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); creatSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = new UserTokenPolicy(credential, profile.getEnvironment()); AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); createSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void creatSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void createSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } public static class UserTokenPolicy implements HttpPipelinePolicy { private final TokenCredential credential; private final AzureEnvironment environment; public UserTokenPolicy(TokenCredential credential, AzureEnvironment environment) { this.credential = credential; this.environment = environment; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(environment.getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); } } }
Does the "mysql flexible" need userToken permanently? If not, I'd not add it to readme as published version cannot be changed. Readme would be cleaned every generation. I could add it but it is not a good choice to maintain here.
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = (context, next) -> { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(profile.getEnvironment().getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); }; AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); creatSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = new UserTokenPolicy(credential, profile.getEnvironment()); AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); createSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void creatSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void createSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } public static class UserTokenPolicy implements HttpPipelinePolicy { private final TokenCredential credential; private final AzureEnvironment environment; public UserTokenPolicy(TokenCredential credential, AzureEnvironment environment) { this.credential = credential; this.environment = environment; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(environment.getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); } } }
Do we reset `updateConfigurationServiceTask` as well?
private void clearCache() { this.gitRepositoryMap.clear(); this.configurationServices.clear(); }
this.configurationServices.clear();
private void clearCache() { this.configurationServices.clear(); this.configurationServiceConfig.reset(); }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private boolean updateConfigurationServiceTask = true; private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringConfigurationServices configurationServices() { return this.configurationServices; } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { if (isEnterpriseTier()) { return withGitConfig((ConfigurationServiceGitProperty) null); } else { return withGitConfig((ConfigServerGitProperty) null); } } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (updateConfigurationServiceTask) { prepareCreateOrUpdateConfigurationService(); } updateConfigurationServiceTask = false; } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { clearCache(); if (isGroupFaulted) { return Mono.empty(); } return refreshAsync().then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withGitConfig(String uri, String branch, List<String> filePatterns) { return withGitConfigRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitConfigRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.gitRepositoryMap.computeIfAbsent(name, key -> new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch) ); updateConfigurationServiceTask = true; return this; } @Override public SpringServiceImpl withGitConfig(ConfigurationServiceGitProperty gitConfig) { gitRepositoryMap.clear(); if (gitConfig != null && CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.gitRepositoryMap.put(repository.name(), repository); } } updateConfigurationServiceTask = true; return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = new ArrayList<>(this.gitRepositoryMap.values()); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private final ConfigurationServiceConfig configurationServiceConfig = new ConfigurationServiceConfig(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { return withGitConfig(null); } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (isInCreateMode() || configurationServiceConfig.needUpdate()) { prepareCreateOrUpdateConfigurationService(); configurationServiceConfig.clearUpdate(); } } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { return Mono .just(true) .map( ignored -> { clearCache(); return ignored; }) .then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withDefaultGitRepository(String uri, String branch, List<String> filePatterns) { return withGitRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.configurationServiceConfig.addRepository( new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch)); return this; } @Override public SpringServiceImpl withGitRepositoryConfig(ConfigurationServiceGitProperty gitConfig) { this.configurationServiceConfig.clearRepositories(); if (gitConfig != null && !CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.configurationServiceConfig.addRepository(repository); } } return this; } @Override public SpringServiceImpl withoutGitRepository(String name) { this.configurationServiceConfig.removeRepository(name); return this; } @Override public SpringServiceImpl withoutGitRepositories() { this.configurationServiceConfig.clearRepositories(); return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = this.configurationServiceConfig.mergeRepositories(); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private class ConfigurationServiceConfig { private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); private final Set<String> repositoriesToDelete = new HashSet<>(); private boolean update; private boolean clearRepositories; boolean needUpdate() { return update; } public void clearUpdate() { this.update = false; } void reset() { this.gitRepositoryMap.clear(); this.update = false; this.repositoriesToDelete.clear(); this.clearRepositories = false; } public void addRepository(ConfigurationServiceGitRepository repository) { this.gitRepositoryMap.putIfAbsent(repository.name(), repository); this.update = true; } public void clearRepositories() { this.gitRepositoryMap.clear(); this.clearRepositories = true; this.update = true; } public void removeRepository(String name) { this.repositoriesToDelete.add(name); this.update = true; } public List<ConfigurationServiceGitRepository> mergeRepositories() { if (this.clearRepositories) { return new ArrayList<>(this.gitRepositoryMap.values()); } else { Map<String, ConfigurationServiceGitRepository> existingGitRepositories = new HashMap<>(); if (isInUpdateMode()) { SpringConfigurationService configurationService = getDefaultConfigurationService(); if (configurationService != null) { List<ConfigurationServiceGitRepository> repositoryList = configurationService.innerModel().properties().settings() == null ? Collections.emptyList() : configurationService.innerModel().properties().settings().gitProperty().repositories(); if (repositoryList != null) { repositoryList.forEach(repository -> existingGitRepositories.put(repository.name(), repository)); } } } existingGitRepositories.putAll(gitRepositoryMap); for (String repositoryToDelete : repositoriesToDelete) { existingGitRepositories.remove(repositoryToDelete); } return new ArrayList<>(existingGitRepositories.values()); } } } }
If this is typical and recommended, should you define it as a static class so that it be easier for user to reuse?
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = (context, next) -> { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(profile.getEnvironment().getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); }; AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); creatSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
};
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = new UserTokenPolicy(credential, profile.getEnvironment()); AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); createSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void creatSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void createSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } public static class UserTokenPolicy implements HttpPipelinePolicy { private final TokenCredential credential; private final AzureEnvironment environment; public UserTokenPolicy(TokenCredential credential, AzureEnvironment environment) { this.credential = credential; this.environment = environment; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(environment.getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); } } }
Readme under samples will not be cleared, see https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/eventgrid/azure-resourcemanager-eventgrid/src/samples And you need that to be published to sample browse https://docs.microsoft.com/en-us/samples/browse/ Readme under root will be cleared, though we should be able to add some way to preserve part of the customized readme, if requirement arise in future.
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = (context, next) -> { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(profile.getEnvironment().getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); }; AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); creatSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = new UserTokenPolicy(credential, profile.getEnvironment()); AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); createSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void creatSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void createSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } public static class UserTokenPolicy implements HttpPipelinePolicy { private final TokenCredential credential; private final AzureEnvironment environment; public UserTokenPolicy(TokenCredential credential, AzureEnvironment environment) { this.credential = credential; this.environment = environment; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(environment.getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); } } }
done
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = (context, next) -> { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(profile.getEnvironment().getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); }; AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); creatSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
};
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = new UserTokenPolicy(credential, profile.getEnvironment()); AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); createSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void creatSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void createSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } public static class UserTokenPolicy implements HttpPipelinePolicy { private final TokenCredential credential; private final AzureEnvironment environment; public UserTokenPolicy(TokenCredential credential, AzureEnvironment environment) { this.credential = credential; this.environment = environment; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(environment.getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); } } }
Added a readme in sample folder https://github.com/Azure/azure-sdk-for-java/pull/28333/files#diff-ba0e6092eadc8fcf817568fec7a412df4b829a7a8dd0b7c28994c94126a384cc
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = (context, next) -> { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(profile.getEnvironment().getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); }; AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); creatSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
public static void main(String[] args) throws Exception { TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) .build(); AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); HttpPipelinePolicy userTokenPolicy = new UserTokenPolicy(credential, profile.getEnvironment()); AzureResourceManager azureResourceManager = AzureResourceManager.authenticate(credential, profile).withDefaultSubscription(); ServiceLinkerManager serviceLinkerManager = ServiceLinkerManager.authenticate(credential, profile); ServiceLinkerManager serviceLinkerManagerWithUserToken = ServiceLinkerManager.configure().withPolicy(userTokenPolicy).authenticate(credential, profile); createSpringCloudAndSQLConnection(azureResourceManager, serviceLinkerManager); createWebAppAndKeyVaultConnectionWithUserIdentity(azureResourceManager, serviceLinkerManagerWithUserToken); }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void creatSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } }
class CreateServiceLinker { private static final String USER_TOKEN_HEADER = "x-ms-serviceconnector-user-token"; /** * Main entry point. * * @param args the parameters */ private static void createSpringCloudAndSQLConnection(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String springServiceName = "spring" + randomString(8); String springAppName = "app" + randomString(8); String sqlServerName = "sqlserver" + randomString(8); String sqlDatabaseName = "sqldb" + randomString(8); String sqlUserName = "sql" + randomString(8); String sqlPassword = "5$Ql" + randomString(8); SpringService springService = azureResourceManager.springServices().define(springServiceName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withSku(SkuName.B0) .create(); SpringApp springApp = springService.apps().define(springAppName) .withDefaultActiveDeployment() .create(); SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withAdministratorLogin(sqlUserName) .withAdministratorPassword(sqlPassword) .create(); SqlDatabase sqlDatabase = sqlServer.databases().define(sqlDatabaseName) .withBasicEdition() .create(); LinkerResource linker = serviceLinkerManager.linkers().define("sql") .withExistingResourceUri(springApp.getActiveDeployment().id()) .withTargetService( new AzureResource() .withId(sqlDatabase.id()) ) .withAuthInfo( new SecretAuthInfo() .withName(sqlUserName) .withSecretInfo( new ValueSecretInfo() .withValue(sqlPassword) ) ) .withClientType(ClientType.SPRING_BOOT) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static void createWebAppAndKeyVaultConnectionWithUserIdentity(AzureResourceManager azureResourceManager, ServiceLinkerManager serviceLinkerManager) { String resourceGroupName = "rg" + randomString(8); Region region = Region.US_EAST; String webAppName = "web" + randomString(8); String keyVaultName = "vault" + randomString(8); String identityName = "identity" + randomString(8); WebApp webApp = azureResourceManager.webApps().define(webAppName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withNewLinuxPlan(PricingTier.BASIC_B1) .withBuiltInImage(RuntimeStack.NODEJS_14_LTS) .create(); Vault vault = azureResourceManager.vaults().define(keyVaultName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withEmptyAccessPolicy() .create(); Identity identity = azureResourceManager.identities().define(identityName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create(); LinkerResource linker = serviceLinkerManager.linkers().define("keyvault") .withExistingResourceUri(webApp.id()) .withTargetService( new AzureResource() .withId(vault.id()) ) .withAuthInfo( new UserAssignedIdentityAuthInfo() .withSubscriptionId(azureResourceManager.subscriptionId()) .withClientId(identity.clientId()) ) .withClientType(ClientType.NODEJS) .create(); System.out.println("Configurations:"); for (SourceConfiguration sourceConfiguration : linker.listConfigurations().configurations()) { System.out.printf("\t%s: %s%n", sourceConfiguration.name(), sourceConfiguration.value()); } } private static String randomString(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } public static class UserTokenPolicy implements HttpPipelinePolicy { private final TokenCredential credential; private final AzureEnvironment environment; public UserTokenPolicy(TokenCredential credential, AzureEnvironment environment) { this.credential = credential; this.environment = environment; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> token = null; String bearerTokenPrefix = "bearer "; String authorization = context.getHttpRequest().getHeaders().getValue("Authorization"); if (authorization != null && authorization.toLowerCase(Locale.ROOT).startsWith(bearerTokenPrefix)) { token = Mono.just(authorization.substring(bearerTokenPrefix.length())); } else { token = credential .getToken(new TokenRequestContext().addScopes(environment.getResourceManagerEndpoint() + "/.default")) .map(AccessToken::getToken); } return token .flatMap(accessToken -> { context.getHttpRequest().getHeaders().set(USER_TOKEN_HEADER, accessToken); return next.process(); }); } } }
I wonder whether use a new model/class will make more sense. For example: Instead of using StoreResult -> use a new class ResponseStatistic, and contain the following properties directly. ![image](https://user-images.githubusercontent.com/64233642/163652271-e88a47f1-db5d-41d6-80b8-756d6f63607c.png)
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult); storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); activityId = request.getActivityId().toString(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } }
storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult);
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult); storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); activityId = request.getActivityId().toString(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null && globalEndpointManager != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext diagnosticsClientContext; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private GatewayStatistics gatewayStatistics; private RequestTimeline gatewayRequestTimeline; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientContext = diagnosticsClientContext; this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientContext = toBeCloned.diagnosticsClientContext; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); } public Duration getDuration() { return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public DiagnosticsClientContext getDiagnosticsClientContext() { return diagnosticsClientContext; } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponse storeResponse, CosmosException exception, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } this.gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); } if (storeResponse != null) { this.gatewayStatistics.statusCode = storeResponse.getStatus(); this.gatewayStatistics.subStatusCode = DirectBridgeInternal.getSubStatusCode(storeResponse); this.gatewayStatistics.sessionToken = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN); this.gatewayStatistics.requestCharge = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.REQUEST_CHARGE); this.gatewayStatistics.requestTimeline = DirectBridgeInternal.getRequestTimeline(storeResponse); this.gatewayStatistics.partitionKeyRangeId = storeResponse.getPartitionKeyRangeId(); this.activityId= storeResponse.getHeaderValue(HttpConstants.HttpHeaders.ACTIVITY_ID); } else if (exception != null) { this.gatewayStatistics.statusCode = exception.getStatusCode(); this.gatewayStatistics.subStatusCode = exception.getSubStatusCode(); this.gatewayStatistics.requestTimeline = this.gatewayRequestTimeline; this.gatewayStatistics.requestCharge= String.valueOf(exception.getRequestCharge()); this.activityId=exception.getActivityId(); } } } public void setGatewayRequestTimeline(RequestTimeline transportRequestTimeline) { this.gatewayRequestTimeline = transportRequestTimeline; } public RequestTimeline getGatewayRequestTimeline() { return this.gatewayRequestTimeline; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = Utils .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd(String identifier, String errorMessage) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.errorMessage = errorMessage; resolutionStatistics.inflightRequest = false; } } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public GatewayStatistics getGatewayStatistics() { return gatewayStatistics; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResult.StoreResultSerializer.class) private StoreResult storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; public StoreResult getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } } public static class SystemInformation { private String usedMemory; private String availableMemory; private String systemCpuLoad; private int availableProcessors; public String getUsedMemory() { return usedMemory; } public String getAvailableMemory() { return availableMemory; } public String getSystemCpuLoad() { return systemCpuLoad; } public int getAvailableProcessors() { return availableProcessors; } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); long requestLatency = statistics .getDuration() .toMillis(); generator.writeStringField("userAgent", Utils.getUserAgent()); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics); try { SystemInformation systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientContext); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String errorMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getErrorMessage() { return errorMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } } public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private String requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public String getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } } public static SystemInformation fetchSystemInformation() { SystemInformation systemInformation = new SystemInformation(); Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; systemInformation.usedMemory = totalMemory - freeMemory + " KB"; systemInformation.availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB"; systemInformation.availableProcessors = runtime.availableProcessors(); systemInformation.systemCpuLoad = CpuMemoryMonitor .getCpuLoad() .toString(); return systemInformation; } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext.DiagnosticsClientConfig diagnosticsClientConfig; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private GatewayStatistics gatewayStatistics; private RequestTimeline gatewayRequestTimeline; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientConfig = diagnosticsClientContext.getConfig(); this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientConfig = toBeCloned.diagnosticsClientConfig; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); } public Duration getDuration() { return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public DiagnosticsClientContext.DiagnosticsClientConfig getDiagnosticsClientConfig() { return diagnosticsClientConfig; } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponse storeResponse, CosmosException exception, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null && globalEndpointManager != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } this.gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); } if (storeResponse != null) { this.gatewayStatistics.statusCode = storeResponse.getStatus(); this.gatewayStatistics.subStatusCode = DirectBridgeInternal.getSubStatusCode(storeResponse); this.gatewayStatistics.sessionToken = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN); this.gatewayStatistics.requestCharge = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.REQUEST_CHARGE); this.gatewayStatistics.requestTimeline = DirectBridgeInternal.getRequestTimeline(storeResponse); this.gatewayStatistics.partitionKeyRangeId = storeResponse.getPartitionKeyRangeId(); this.activityId= storeResponse.getHeaderValue(HttpConstants.HttpHeaders.ACTIVITY_ID); } else if (exception != null) { this.gatewayStatistics.statusCode = exception.getStatusCode(); this.gatewayStatistics.subStatusCode = exception.getSubStatusCode(); this.gatewayStatistics.requestTimeline = this.gatewayRequestTimeline; this.gatewayStatistics.requestCharge= String.valueOf(exception.getRequestCharge()); this.activityId=exception.getActivityId(); } } } public void setGatewayRequestTimeline(RequestTimeline transportRequestTimeline) { this.gatewayRequestTimeline = transportRequestTimeline; } public RequestTimeline getGatewayRequestTimeline() { return this.gatewayRequestTimeline; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = Utils .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd(String identifier, String errorMessage) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.errorMessage = errorMessage; resolutionStatistics.inflightRequest = false; } } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public GatewayStatistics getGatewayStatistics() { return gatewayStatistics; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResult.StoreResultSerializer.class) private StoreResult storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; public StoreResult getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } } public static class SystemInformation { private String usedMemory; private String availableMemory; private String systemCpuLoad; private int availableProcessors; public String getUsedMemory() { return usedMemory; } public String getAvailableMemory() { return availableMemory; } public String getSystemCpuLoad() { return systemCpuLoad; } public int getAvailableProcessors() { return availableProcessors; } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); long requestLatency = statistics .getDuration() .toMillis(); generator.writeStringField("userAgent", Utils.getUserAgent()); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics); try { SystemInformation systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientConfig); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String errorMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getErrorMessage() { return errorMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } } public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private String requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public String getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } } public static SystemInformation fetchSystemInformation() { SystemInformation systemInformation = new SystemInformation(); Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; systemInformation.usedMemory = totalMemory - freeMemory + " KB"; systemInformation.availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB"; systemInformation.availableProcessors = runtime.availableProcessors(); systemInformation.systemCpuLoad = CpuMemoryMonitor .getCpuLoad() .toString(); return systemInformation; } }
Actually not, since we serialize all the fields from `StoreResult`, so making a new model class would just be a copy of `StoreResult`, doesn't give us any advantages. In addition to that, `StoreResult` doesn't contains any circular references, so we can use it as it is. Thoughts? In my opinion, it rather makes a more compelling case for `StoreResponse` - since it contains fields that we don't need for sure, like `content`, `responseHeaderNames` and `responseHeaderValues` But if we go into the copy path, it may take more time for this issue. I am interested in making those changes, however, would not want to change a lot since we want to release this as a hotfix. Open to making those changes in our work on re-modeling `CosmosDiagnostics` altogether.
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult); storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); activityId = request.getActivityId().toString(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } }
storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult);
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult); storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); activityId = request.getActivityId().toString(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null && globalEndpointManager != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext diagnosticsClientContext; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private GatewayStatistics gatewayStatistics; private RequestTimeline gatewayRequestTimeline; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientContext = diagnosticsClientContext; this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientContext = toBeCloned.diagnosticsClientContext; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); } public Duration getDuration() { return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public DiagnosticsClientContext getDiagnosticsClientContext() { return diagnosticsClientContext; } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponse storeResponse, CosmosException exception, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } this.gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); } if (storeResponse != null) { this.gatewayStatistics.statusCode = storeResponse.getStatus(); this.gatewayStatistics.subStatusCode = DirectBridgeInternal.getSubStatusCode(storeResponse); this.gatewayStatistics.sessionToken = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN); this.gatewayStatistics.requestCharge = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.REQUEST_CHARGE); this.gatewayStatistics.requestTimeline = DirectBridgeInternal.getRequestTimeline(storeResponse); this.gatewayStatistics.partitionKeyRangeId = storeResponse.getPartitionKeyRangeId(); this.activityId= storeResponse.getHeaderValue(HttpConstants.HttpHeaders.ACTIVITY_ID); } else if (exception != null) { this.gatewayStatistics.statusCode = exception.getStatusCode(); this.gatewayStatistics.subStatusCode = exception.getSubStatusCode(); this.gatewayStatistics.requestTimeline = this.gatewayRequestTimeline; this.gatewayStatistics.requestCharge= String.valueOf(exception.getRequestCharge()); this.activityId=exception.getActivityId(); } } } public void setGatewayRequestTimeline(RequestTimeline transportRequestTimeline) { this.gatewayRequestTimeline = transportRequestTimeline; } public RequestTimeline getGatewayRequestTimeline() { return this.gatewayRequestTimeline; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = Utils .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd(String identifier, String errorMessage) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.errorMessage = errorMessage; resolutionStatistics.inflightRequest = false; } } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public GatewayStatistics getGatewayStatistics() { return gatewayStatistics; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResult.StoreResultSerializer.class) private StoreResult storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; public StoreResult getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } } public static class SystemInformation { private String usedMemory; private String availableMemory; private String systemCpuLoad; private int availableProcessors; public String getUsedMemory() { return usedMemory; } public String getAvailableMemory() { return availableMemory; } public String getSystemCpuLoad() { return systemCpuLoad; } public int getAvailableProcessors() { return availableProcessors; } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); long requestLatency = statistics .getDuration() .toMillis(); generator.writeStringField("userAgent", Utils.getUserAgent()); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics); try { SystemInformation systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientContext); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String errorMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getErrorMessage() { return errorMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } } public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private String requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public String getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } } public static SystemInformation fetchSystemInformation() { SystemInformation systemInformation = new SystemInformation(); Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; systemInformation.usedMemory = totalMemory - freeMemory + " KB"; systemInformation.availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB"; systemInformation.availableProcessors = runtime.availableProcessors(); systemInformation.systemCpuLoad = CpuMemoryMonitor .getCpuLoad() .toString(); return systemInformation; } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext.DiagnosticsClientConfig diagnosticsClientConfig; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private GatewayStatistics gatewayStatistics; private RequestTimeline gatewayRequestTimeline; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientConfig = diagnosticsClientContext.getConfig(); this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientConfig = toBeCloned.diagnosticsClientConfig; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); } public Duration getDuration() { return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public DiagnosticsClientContext.DiagnosticsClientConfig getDiagnosticsClientConfig() { return diagnosticsClientConfig; } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponse storeResponse, CosmosException exception, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null && globalEndpointManager != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } this.gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); } if (storeResponse != null) { this.gatewayStatistics.statusCode = storeResponse.getStatus(); this.gatewayStatistics.subStatusCode = DirectBridgeInternal.getSubStatusCode(storeResponse); this.gatewayStatistics.sessionToken = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN); this.gatewayStatistics.requestCharge = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.REQUEST_CHARGE); this.gatewayStatistics.requestTimeline = DirectBridgeInternal.getRequestTimeline(storeResponse); this.gatewayStatistics.partitionKeyRangeId = storeResponse.getPartitionKeyRangeId(); this.activityId= storeResponse.getHeaderValue(HttpConstants.HttpHeaders.ACTIVITY_ID); } else if (exception != null) { this.gatewayStatistics.statusCode = exception.getStatusCode(); this.gatewayStatistics.subStatusCode = exception.getSubStatusCode(); this.gatewayStatistics.requestTimeline = this.gatewayRequestTimeline; this.gatewayStatistics.requestCharge= String.valueOf(exception.getRequestCharge()); this.activityId=exception.getActivityId(); } } } public void setGatewayRequestTimeline(RequestTimeline transportRequestTimeline) { this.gatewayRequestTimeline = transportRequestTimeline; } public RequestTimeline getGatewayRequestTimeline() { return this.gatewayRequestTimeline; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = Utils .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd(String identifier, String errorMessage) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.errorMessage = errorMessage; resolutionStatistics.inflightRequest = false; } } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public GatewayStatistics getGatewayStatistics() { return gatewayStatistics; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResult.StoreResultSerializer.class) private StoreResult storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; public StoreResult getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } } public static class SystemInformation { private String usedMemory; private String availableMemory; private String systemCpuLoad; private int availableProcessors; public String getUsedMemory() { return usedMemory; } public String getAvailableMemory() { return availableMemory; } public String getSystemCpuLoad() { return systemCpuLoad; } public int getAvailableProcessors() { return availableProcessors; } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); long requestLatency = statistics .getDuration() .toMillis(); generator.writeStringField("userAgent", Utils.getUserAgent()); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics); try { SystemInformation systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientConfig); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String errorMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getErrorMessage() { return errorMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } } public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private String requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public String getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } } public static SystemInformation fetchSystemInformation() { SystemInformation systemInformation = new SystemInformation(); Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; systemInformation.usedMemory = totalMemory - freeMemory + " KB"; systemInformation.availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB"; systemInformation.availableProcessors = runtime.availableProcessors(); systemInformation.systemCpuLoad = CpuMemoryMonitor .getCpuLoad() .toString(); return systemInformation; } }
+1 on Kushagra's comment. To me StoreResult is basically the "model". I agree that making changes to StoreResponse and creating model for diagnostics there is preferrable.
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult); storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); activityId = request.getActivityId().toString(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } }
storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult);
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult); storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); activityId = request.getActivityId().toString(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null && globalEndpointManager != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext diagnosticsClientContext; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private GatewayStatistics gatewayStatistics; private RequestTimeline gatewayRequestTimeline; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientContext = diagnosticsClientContext; this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientContext = toBeCloned.diagnosticsClientContext; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); } public Duration getDuration() { return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public DiagnosticsClientContext getDiagnosticsClientContext() { return diagnosticsClientContext; } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponse storeResponse, CosmosException exception, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } this.gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); } if (storeResponse != null) { this.gatewayStatistics.statusCode = storeResponse.getStatus(); this.gatewayStatistics.subStatusCode = DirectBridgeInternal.getSubStatusCode(storeResponse); this.gatewayStatistics.sessionToken = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN); this.gatewayStatistics.requestCharge = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.REQUEST_CHARGE); this.gatewayStatistics.requestTimeline = DirectBridgeInternal.getRequestTimeline(storeResponse); this.gatewayStatistics.partitionKeyRangeId = storeResponse.getPartitionKeyRangeId(); this.activityId= storeResponse.getHeaderValue(HttpConstants.HttpHeaders.ACTIVITY_ID); } else if (exception != null) { this.gatewayStatistics.statusCode = exception.getStatusCode(); this.gatewayStatistics.subStatusCode = exception.getSubStatusCode(); this.gatewayStatistics.requestTimeline = this.gatewayRequestTimeline; this.gatewayStatistics.requestCharge= String.valueOf(exception.getRequestCharge()); this.activityId=exception.getActivityId(); } } } public void setGatewayRequestTimeline(RequestTimeline transportRequestTimeline) { this.gatewayRequestTimeline = transportRequestTimeline; } public RequestTimeline getGatewayRequestTimeline() { return this.gatewayRequestTimeline; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = Utils .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd(String identifier, String errorMessage) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.errorMessage = errorMessage; resolutionStatistics.inflightRequest = false; } } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public GatewayStatistics getGatewayStatistics() { return gatewayStatistics; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResult.StoreResultSerializer.class) private StoreResult storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; public StoreResult getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } } public static class SystemInformation { private String usedMemory; private String availableMemory; private String systemCpuLoad; private int availableProcessors; public String getUsedMemory() { return usedMemory; } public String getAvailableMemory() { return availableMemory; } public String getSystemCpuLoad() { return systemCpuLoad; } public int getAvailableProcessors() { return availableProcessors; } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); long requestLatency = statistics .getDuration() .toMillis(); generator.writeStringField("userAgent", Utils.getUserAgent()); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics); try { SystemInformation systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientContext); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String errorMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getErrorMessage() { return errorMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } } public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private String requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public String getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } } public static SystemInformation fetchSystemInformation() { SystemInformation systemInformation = new SystemInformation(); Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; systemInformation.usedMemory = totalMemory - freeMemory + " KB"; systemInformation.availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB"; systemInformation.availableProcessors = runtime.availableProcessors(); systemInformation.systemCpuLoad = CpuMemoryMonitor .getCpuLoad() .toString(); return systemInformation; } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext.DiagnosticsClientConfig diagnosticsClientConfig; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private GatewayStatistics gatewayStatistics; private RequestTimeline gatewayRequestTimeline; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientConfig = diagnosticsClientContext.getConfig(); this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientConfig = toBeCloned.diagnosticsClientConfig; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); } public Duration getDuration() { return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public DiagnosticsClientContext.DiagnosticsClientConfig getDiagnosticsClientConfig() { return diagnosticsClientConfig; } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponse storeResponse, CosmosException exception, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null && globalEndpointManager != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } this.gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); } if (storeResponse != null) { this.gatewayStatistics.statusCode = storeResponse.getStatus(); this.gatewayStatistics.subStatusCode = DirectBridgeInternal.getSubStatusCode(storeResponse); this.gatewayStatistics.sessionToken = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN); this.gatewayStatistics.requestCharge = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.REQUEST_CHARGE); this.gatewayStatistics.requestTimeline = DirectBridgeInternal.getRequestTimeline(storeResponse); this.gatewayStatistics.partitionKeyRangeId = storeResponse.getPartitionKeyRangeId(); this.activityId= storeResponse.getHeaderValue(HttpConstants.HttpHeaders.ACTIVITY_ID); } else if (exception != null) { this.gatewayStatistics.statusCode = exception.getStatusCode(); this.gatewayStatistics.subStatusCode = exception.getSubStatusCode(); this.gatewayStatistics.requestTimeline = this.gatewayRequestTimeline; this.gatewayStatistics.requestCharge= String.valueOf(exception.getRequestCharge()); this.activityId=exception.getActivityId(); } } } public void setGatewayRequestTimeline(RequestTimeline transportRequestTimeline) { this.gatewayRequestTimeline = transportRequestTimeline; } public RequestTimeline getGatewayRequestTimeline() { return this.gatewayRequestTimeline; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = Utils .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd(String identifier, String errorMessage) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.errorMessage = errorMessage; resolutionStatistics.inflightRequest = false; } } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public GatewayStatistics getGatewayStatistics() { return gatewayStatistics; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResult.StoreResultSerializer.class) private StoreResult storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; public StoreResult getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } } public static class SystemInformation { private String usedMemory; private String availableMemory; private String systemCpuLoad; private int availableProcessors; public String getUsedMemory() { return usedMemory; } public String getAvailableMemory() { return availableMemory; } public String getSystemCpuLoad() { return systemCpuLoad; } public int getAvailableProcessors() { return availableProcessors; } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); long requestLatency = statistics .getDuration() .toMillis(); generator.writeStringField("userAgent", Utils.getUserAgent()); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics); try { SystemInformation systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientConfig); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String errorMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getErrorMessage() { return errorMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } } public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private String requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public String getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } } public static SystemInformation fetchSystemInformation() { SystemInformation systemInformation = new SystemInformation(); Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; systemInformation.usedMemory = totalMemory - freeMemory + " KB"; systemInformation.availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB"; systemInformation.availableProcessors = runtime.availableProcessors(); systemInformation.systemCpuLoad = CpuMemoryMonitor .getCpuLoad() .toString(); return systemInformation; } }
yea, similar thoughts for storeResponse and cosmosException. But to me, StoreResponseStatistics itself is the model, but not StoreResult. We can just extract all the info we cared directly into StoreResponseStatistics, for example SessionToken referenced in storeResult vs sessionToken string in StoreResponseStatistics.
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult); storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); activityId = request.getActivityId().toString(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } }
storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult);
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = StoreResult.createSerializableStoreResult(storeResult); storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); activityId = request.getActivityId().toString(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null && globalEndpointManager != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext diagnosticsClientContext; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private GatewayStatistics gatewayStatistics; private RequestTimeline gatewayRequestTimeline; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientContext = diagnosticsClientContext; this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientContext = toBeCloned.diagnosticsClientContext; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); } public Duration getDuration() { return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public DiagnosticsClientContext getDiagnosticsClientContext() { return diagnosticsClientContext; } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponse storeResponse, CosmosException exception, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } this.gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); } if (storeResponse != null) { this.gatewayStatistics.statusCode = storeResponse.getStatus(); this.gatewayStatistics.subStatusCode = DirectBridgeInternal.getSubStatusCode(storeResponse); this.gatewayStatistics.sessionToken = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN); this.gatewayStatistics.requestCharge = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.REQUEST_CHARGE); this.gatewayStatistics.requestTimeline = DirectBridgeInternal.getRequestTimeline(storeResponse); this.gatewayStatistics.partitionKeyRangeId = storeResponse.getPartitionKeyRangeId(); this.activityId= storeResponse.getHeaderValue(HttpConstants.HttpHeaders.ACTIVITY_ID); } else if (exception != null) { this.gatewayStatistics.statusCode = exception.getStatusCode(); this.gatewayStatistics.subStatusCode = exception.getSubStatusCode(); this.gatewayStatistics.requestTimeline = this.gatewayRequestTimeline; this.gatewayStatistics.requestCharge= String.valueOf(exception.getRequestCharge()); this.activityId=exception.getActivityId(); } } } public void setGatewayRequestTimeline(RequestTimeline transportRequestTimeline) { this.gatewayRequestTimeline = transportRequestTimeline; } public RequestTimeline getGatewayRequestTimeline() { return this.gatewayRequestTimeline; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = Utils .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd(String identifier, String errorMessage) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.errorMessage = errorMessage; resolutionStatistics.inflightRequest = false; } } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public GatewayStatistics getGatewayStatistics() { return gatewayStatistics; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResult.StoreResultSerializer.class) private StoreResult storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; public StoreResult getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } } public static class SystemInformation { private String usedMemory; private String availableMemory; private String systemCpuLoad; private int availableProcessors; public String getUsedMemory() { return usedMemory; } public String getAvailableMemory() { return availableMemory; } public String getSystemCpuLoad() { return systemCpuLoad; } public int getAvailableProcessors() { return availableProcessors; } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); long requestLatency = statistics .getDuration() .toMillis(); generator.writeStringField("userAgent", Utils.getUserAgent()); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics); try { SystemInformation systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientContext); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String errorMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getErrorMessage() { return errorMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } } public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private String requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public String getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } } public static SystemInformation fetchSystemInformation() { SystemInformation systemInformation = new SystemInformation(); Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; systemInformation.usedMemory = totalMemory - freeMemory + " KB"; systemInformation.availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB"; systemInformation.availableProcessors = runtime.availableProcessors(); systemInformation.systemCpuLoad = CpuMemoryMonitor .getCpuLoad() .toString(); return systemInformation; } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext.DiagnosticsClientConfig diagnosticsClientConfig; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private GatewayStatistics gatewayStatistics; private RequestTimeline gatewayRequestTimeline; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientConfig = diagnosticsClientContext.getConfig(); this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientConfig = toBeCloned.diagnosticsClientConfig; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); } public Duration getDuration() { return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public DiagnosticsClientContext.DiagnosticsClientConfig getDiagnosticsClientConfig() { return diagnosticsClientConfig; } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponse storeResponse, CosmosException exception, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null && globalEndpointManager != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } this.gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); } if (storeResponse != null) { this.gatewayStatistics.statusCode = storeResponse.getStatus(); this.gatewayStatistics.subStatusCode = DirectBridgeInternal.getSubStatusCode(storeResponse); this.gatewayStatistics.sessionToken = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN); this.gatewayStatistics.requestCharge = storeResponse .getHeaderValue(HttpConstants.HttpHeaders.REQUEST_CHARGE); this.gatewayStatistics.requestTimeline = DirectBridgeInternal.getRequestTimeline(storeResponse); this.gatewayStatistics.partitionKeyRangeId = storeResponse.getPartitionKeyRangeId(); this.activityId= storeResponse.getHeaderValue(HttpConstants.HttpHeaders.ACTIVITY_ID); } else if (exception != null) { this.gatewayStatistics.statusCode = exception.getStatusCode(); this.gatewayStatistics.subStatusCode = exception.getSubStatusCode(); this.gatewayStatistics.requestTimeline = this.gatewayRequestTimeline; this.gatewayStatistics.requestCharge= String.valueOf(exception.getRequestCharge()); this.activityId=exception.getActivityId(); } } } public void setGatewayRequestTimeline(RequestTimeline transportRequestTimeline) { this.gatewayRequestTimeline = transportRequestTimeline; } public RequestTimeline getGatewayRequestTimeline() { return this.gatewayRequestTimeline; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = Utils .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd(String identifier, String errorMessage) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.errorMessage = errorMessage; resolutionStatistics.inflightRequest = false; } } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public GatewayStatistics getGatewayStatistics() { return gatewayStatistics; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResult.StoreResultSerializer.class) private StoreResult storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; public StoreResult getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } } public static class SystemInformation { private String usedMemory; private String availableMemory; private String systemCpuLoad; private int availableProcessors; public String getUsedMemory() { return usedMemory; } public String getAvailableMemory() { return availableMemory; } public String getSystemCpuLoad() { return systemCpuLoad; } public int getAvailableProcessors() { return availableProcessors; } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); long requestLatency = statistics .getDuration() .toMillis(); generator.writeStringField("userAgent", Utils.getUserAgent()); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics); try { SystemInformation systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientConfig); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String errorMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getErrorMessage() { return errorMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } } public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private String requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public String getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } } public static SystemInformation fetchSystemInformation() { SystemInformation systemInformation = new SystemInformation(); Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; systemInformation.usedMemory = totalMemory - freeMemory + " KB"; systemInformation.availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB"; systemInformation.availableProcessors = runtime.availableProcessors(); systemInformation.systemCpuLoad = CpuMemoryMonitor .getCpuLoad() .toString(); return systemInformation; } }
is `.` actually valid? Or was there just a bug in the regex?
private static boolean isValidTenantCharacter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '.') || (c == '-'); }
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '.') || (c == '-');
private static boolean isValidTenantCharacter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '.') || (c == '-'); }
class ValidationUtil { public static void validate(String className, Map<String, Object> parameters, ClientLogger logger) { List<String> missing = new ArrayList<>(); for (Map.Entry<String, Object> entry : parameters.entrySet()) { if (entry.getValue() == null) { missing.add(entry.getKey()); } } if (missing.size() > 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Must provide non-null values for " + String.join(", ", missing) + " properties in " + className)); } } public static void validateAuthHost(String authHost, ClientLogger logger) { try { new URI(authHost); } catch (URISyntaxException e) { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide a valid URI for authority host.", e)); } if (!authHost.startsWith("https")) { throw logger.logExceptionAsError( new IllegalArgumentException("Authority host must use https scheme.")); } } public static void validateTenantIdCharacterRange(String id, ClientLogger logger) { if (id != null) { for (int i = 0; i < id.length(); i++) { if (!isValidTenantCharacter(id.charAt(i))) { throw logger.logExceptionAsError( new IllegalArgumentException( "Invalid tenant id provided. You can locate your tenant id by following the instructions" + " listed here: https: } } } } public static void validateInteractiveBrowserRedirectUrlSetup(Integer port, String redirectUrl, ClientLogger logger) { if (port != null && redirectUrl != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Port and Redirect URL cannot be configured at the same time. " + "Port is deprecated now. Use the redirectUrl setter to specify" + " the redirect URL on the builder.")); } } }
class ValidationUtil { public static void validate(String className, Map<String, Object> parameters, ClientLogger logger) { List<String> missing = new ArrayList<>(); for (Map.Entry<String, Object> entry : parameters.entrySet()) { if (entry.getValue() == null) { missing.add(entry.getKey()); } } if (missing.size() > 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Must provide non-null values for " + String.join(", ", missing) + " properties in " + className)); } } public static void validateAuthHost(String authHost, ClientLogger logger) { try { new URI(authHost); } catch (URISyntaxException e) { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide a valid URI for authority host.", e)); } if (!authHost.startsWith("https")) { throw logger.logExceptionAsError( new IllegalArgumentException("Authority host must use https scheme.")); } } public static void validateTenantIdCharacterRange(String id, ClientLogger logger) { if (id != null) { for (int i = 0; i < id.length(); i++) { if (!isValidTenantCharacter(id.charAt(i))) { throw logger.logExceptionAsError( new IllegalArgumentException( "Invalid tenant id provided. You can locate your tenant id by following the instructions" + " listed here: https: } } } } public static void validateInteractiveBrowserRedirectUrlSetup(Integer port, String redirectUrl, ClientLogger logger) { if (port != null && redirectUrl != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Port and Redirect URL cannot be configured at the same time. " + "Port is deprecated now. Use the redirectUrl setter to specify" + " the redirect URL on the builder.")); } } }
Does refresh needed? It is an extra GET?
public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { clearCache(); if (isGroupFaulted) { return Mono.empty(); } return refreshAsync().then(); }
return refreshAsync().then();
public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { return Mono .just(true) .map( ignored -> { clearCache(); return ignored; }) .then(); }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private boolean updateConfigurationServiceTask = true; private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringConfigurationServices configurationServices() { return this.configurationServices; } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { if (isEnterpriseTier()) { return withGitConfig((ConfigurationServiceGitProperty) null); } else { return withGitConfig((ConfigServerGitProperty) null); } } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (updateConfigurationServiceTask) { prepareCreateOrUpdateConfigurationService(); } updateConfigurationServiceTask = false; } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withGitConfig(String uri, String branch, List<String> filePatterns) { return withGitConfigRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitConfigRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.gitRepositoryMap.computeIfAbsent(name, key -> new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch) ); updateConfigurationServiceTask = true; return this; } @Override public SpringServiceImpl withGitConfig(ConfigurationServiceGitProperty gitConfig) { gitRepositoryMap.clear(); if (gitConfig != null && CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.gitRepositoryMap.put(repository.name(), repository); } } updateConfigurationServiceTask = true; return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = new ArrayList<>(this.gitRepositoryMap.values()); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.gitRepositoryMap.clear(); this.configurationServices.clear(); } }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private final ConfigurationServiceConfig configurationServiceConfig = new ConfigurationServiceConfig(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { return withGitConfig(null); } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (isInCreateMode() || configurationServiceConfig.needUpdate()) { prepareCreateOrUpdateConfigurationService(); configurationServiceConfig.clearUpdate(); } } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withDefaultGitRepository(String uri, String branch, List<String> filePatterns) { return withGitRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.configurationServiceConfig.addRepository( new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch)); return this; } @Override public SpringServiceImpl withGitRepositoryConfig(ConfigurationServiceGitProperty gitConfig) { this.configurationServiceConfig.clearRepositories(); if (gitConfig != null && !CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.configurationServiceConfig.addRepository(repository); } } return this; } @Override public SpringServiceImpl withoutGitRepository(String name) { this.configurationServiceConfig.removeRepository(name); return this; } @Override public SpringServiceImpl withoutGitRepositories() { this.configurationServiceConfig.clearRepositories(); return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = this.configurationServiceConfig.mergeRepositories(); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.configurationServices.clear(); this.configurationServiceConfig.reset(); } private class ConfigurationServiceConfig { private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); private final Set<String> repositoriesToDelete = new HashSet<>(); private boolean update; private boolean clearRepositories; boolean needUpdate() { return update; } public void clearUpdate() { this.update = false; } void reset() { this.gitRepositoryMap.clear(); this.update = false; this.repositoriesToDelete.clear(); this.clearRepositories = false; } public void addRepository(ConfigurationServiceGitRepository repository) { this.gitRepositoryMap.putIfAbsent(repository.name(), repository); this.update = true; } public void clearRepositories() { this.gitRepositoryMap.clear(); this.clearRepositories = true; this.update = true; } public void removeRepository(String name) { this.repositoriesToDelete.add(name); this.update = true; } public List<ConfigurationServiceGitRepository> mergeRepositories() { if (this.clearRepositories) { return new ArrayList<>(this.gitRepositoryMap.values()); } else { Map<String, ConfigurationServiceGitRepository> existingGitRepositories = new HashMap<>(); if (isInUpdateMode()) { SpringConfigurationService configurationService = getDefaultConfigurationService(); if (configurationService != null) { List<ConfigurationServiceGitRepository> repositoryList = configurationService.innerModel().properties().settings() == null ? Collections.emptyList() : configurationService.innerModel().properties().settings().gitProperty().repositories(); if (repositoryList != null) { repositoryList.forEach(repository -> existingGitRepositories.put(repository.name(), repository)); } } } existingGitRepositories.putAll(gitRepositoryMap); for (String repositoryToDelete : repositoriesToDelete) { existingGitRepositories.remove(repositoryToDelete); } return new ArrayList<>(existingGitRepositories.values()); } } } }
yes, it is an accepted character for tenant ids.
private static boolean isValidTenantCharacter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '.') || (c == '-'); }
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '.') || (c == '-');
private static boolean isValidTenantCharacter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '.') || (c == '-'); }
class ValidationUtil { public static void validate(String className, Map<String, Object> parameters, ClientLogger logger) { List<String> missing = new ArrayList<>(); for (Map.Entry<String, Object> entry : parameters.entrySet()) { if (entry.getValue() == null) { missing.add(entry.getKey()); } } if (missing.size() > 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Must provide non-null values for " + String.join(", ", missing) + " properties in " + className)); } } public static void validateAuthHost(String authHost, ClientLogger logger) { try { new URI(authHost); } catch (URISyntaxException e) { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide a valid URI for authority host.", e)); } if (!authHost.startsWith("https")) { throw logger.logExceptionAsError( new IllegalArgumentException("Authority host must use https scheme.")); } } public static void validateTenantIdCharacterRange(String id, ClientLogger logger) { if (id != null) { for (int i = 0; i < id.length(); i++) { if (!isValidTenantCharacter(id.charAt(i))) { throw logger.logExceptionAsError( new IllegalArgumentException( "Invalid tenant id provided. You can locate your tenant id by following the instructions" + " listed here: https: } } } } public static void validateInteractiveBrowserRedirectUrlSetup(Integer port, String redirectUrl, ClientLogger logger) { if (port != null && redirectUrl != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Port and Redirect URL cannot be configured at the same time. " + "Port is deprecated now. Use the redirectUrl setter to specify" + " the redirect URL on the builder.")); } } }
class ValidationUtil { public static void validate(String className, Map<String, Object> parameters, ClientLogger logger) { List<String> missing = new ArrayList<>(); for (Map.Entry<String, Object> entry : parameters.entrySet()) { if (entry.getValue() == null) { missing.add(entry.getKey()); } } if (missing.size() > 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Must provide non-null values for " + String.join(", ", missing) + " properties in " + className)); } } public static void validateAuthHost(String authHost, ClientLogger logger) { try { new URI(authHost); } catch (URISyntaxException e) { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide a valid URI for authority host.", e)); } if (!authHost.startsWith("https")) { throw logger.logExceptionAsError( new IllegalArgumentException("Authority host must use https scheme.")); } } public static void validateTenantIdCharacterRange(String id, ClientLogger logger) { if (id != null) { for (int i = 0; i < id.length(); i++) { if (!isValidTenantCharacter(id.charAt(i))) { throw logger.logExceptionAsError( new IllegalArgumentException( "Invalid tenant id provided. You can locate your tenant id by following the instructions" + " listed here: https: } } } } public static void validateInteractiveBrowserRedirectUrlSetup(Integer port, String redirectUrl, ClientLogger logger) { if (port != null && redirectUrl != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Port and Redirect URL cannot be configured at the same time. " + "Port is deprecated now. Use the redirectUrl setter to specify" + " the redirect URL on the builder.")); } } }
Does not support Enterprise Tier deployment due to the amount of code, will support it in next individual PR.
public SpringAppDeploymentImpl withJarFile(File jar) { if (service().isEnterpriseTier()) { throw new UnsupportedOperationException("Enterprise tier artifact deployment not supported yet."); } else { ensureSource(UserSourceType.JAR); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorage(jar, option) .then(context.voidMono()); }) ); } return this; }
throw new UnsupportedOperationException("Enterprise tier artifact deployment not supported yet.");
public SpringAppDeploymentImpl withJarFile(File jar) { if (service().isEnterpriseTier()) { throw new UnsupportedOperationException("Enterprise tier artifact deployment not supported yet."); } else { ensureSource(UserSourceType.JAR); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorage(jar, option) .then(context.voidMono()); }) ); } return this; }
class SpringAppDeploymentImpl extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp> implements SpringAppDeployment, SpringAppDeployment.Definition<SpringAppImpl, SpringAppDeploymentImpl>, SpringAppDeployment.Update { SpringAppDeploymentImpl(String name, SpringAppImpl parent, DeploymentResourceInner innerObject) { super(name, parent, innerObject); } @Override public String appName() { if (innerModel().properties() == null) { return null; } return innerModel().name(); } @Override public DeploymentSettings settings() { if (innerModel().properties() == null) { return null; } return innerModel().properties().deploymentSettings(); } @Override public DeploymentResourceStatus status() { if (innerModel().properties() == null) { return null; } return innerModel().properties().status(); } @Override public boolean isActive() { if (innerModel().properties() == null) { return false; } return innerModel().properties().active(); } @Override public List<DeploymentInstance> instances() { if (innerModel().properties() == null) { return null; } return innerModel().properties().instances(); } @Override public void start() { startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().serviceClient().getDeployments().startAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void stop() { stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().serviceClient().getDeployments().stopAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void restart() { restartAsync().block(); } @Override public Mono<Void> restartAsync() { return manager().serviceClient().getDeployments().restartAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String getLogFileUrl() { return getLogFileUrlAsync().block(); } @Override public Mono<String> getLogFileUrlAsync() { return manager().serviceClient().getDeployments().getLogFileUrlAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ) .map(LogFileUrlResponseInner::url); } private void ensureDeploySettings() { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().deploymentSettings() == null) { innerModel().properties().withDeploymentSettings(new DeploymentSettings()); } } private void ensureSource() { ensureSource(null); } private void ensureSource(UserSourceType type) { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().source() == null) { if (type == UserSourceType.JAR) { innerModel().properties().withSource(new JarUploadedUserSourceInfo()); } else if (type == UserSourceType.SOURCE) { innerModel().properties().withSource(new SourceUploadedUserSourceInfo()); } else if (type == UserSourceType.NET_CORE_ZIP) { innerModel().properties().withSource(new NetCoreZipUploadedUserSourceInfo()); } else if (type == UserSourceType.BUILD_RESULT) { innerModel().properties().withSource(new BuildResultUserSourceInfo()); } else { innerModel().properties().withSource(new UserSourceInfo()); } } } private ShareFileAsyncClient createShareFileAsyncClient(ResourceUploadDefinition option) { return new ShareFileClientBuilder() .endpoint(option.uploadUrl()) .httpClient(manager().httpPipeline().getHttpClient()) .buildFileAsyncClient(); } private Mono<Void> uploadToStorage(File source, ResourceUploadDefinition option) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; try { uploadedUserSourceInfo.withRelativePath(option.relativePath()); ShareFileAsyncClient shareFileAsyncClient = createShareFileAsyncClient(option); return shareFileAsyncClient.create(source.length()) .flatMap(fileInfo -> shareFileAsyncClient.uploadFromFile(source.getAbsolutePath())) .then(Mono.empty()); } catch (Exception e) { return Mono.error(e); } } else { return Mono.empty(); } } @Override @Override public SpringAppDeploymentImpl withExistingSource(UserSourceType type, String relativePath) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); UserSourceInfo sourceInfo = innerModel().properties().source(); if (sourceInfo instanceof BuildResultUserSourceInfo) { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) sourceInfo; userSourceInfo.withBuildResultId(relativePath); } } else { ensureSource(type); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRelativePath(relativePath); } } return this; } private boolean isEnterpriseTier() { return service().isEnterpriseTier(); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz) { ensureSource(UserSourceType.SOURCE); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> uploadToStorage(sourceCodeTarGz, option) .then(context.voidMono())) ); return this; } @Override public SpringAppDeploymentImpl withTargetModule(String moduleName) { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(moduleName); } return this; } @Override public SpringAppDeploymentImpl withSingleModule() { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(null); } return this; } @Override public SpringAppDeploymentImpl withInstance(int count) { if (innerModel().sku() == null) { innerModel().withSku(parent().parent().sku()); } if (innerModel().sku() == null) { innerModel().withSku(new Sku().withName("B0")); } innerModel().sku().withCapacity(count); return this; } @Override public SpringAppDeploymentImpl withCpu(int cpuCount) { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } innerModel().properties().deploymentSettings().resourceRequests().withCpu(String.valueOf(cpuCount)); return this; } @Override public SpringAppDeploymentImpl withMemory(int sizeInGB) { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } innerModel().properties().deploymentSettings().resourceRequests().withMemory(String.format("%dGi", sizeInGB)); return this; } @Override public SpringAppDeploymentImpl withRuntime(RuntimeVersion version) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof NetCoreZipUploadedUserSourceInfo) { NetCoreZipUploadedUserSourceInfo uploadedUserSourceInfo = (NetCoreZipUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo uploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } return this; } @Override public SpringAppDeploymentImpl withJvmOptions(String jvmOptions) { ensureSource(UserSourceType.JAR); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withJvmOptions(jvmOptions); } return this; } private void ensureEnvironments() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().environmentVariables() == null) { innerModel().properties().deploymentSettings().withEnvironmentVariables(new HashMap<>()); } } @Override public SpringAppDeploymentImpl withEnvironment(String key, String value) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().put(key, value); return this; } @Override public SpringAppDeploymentImpl withoutEnvironment(String key) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().remove(key); return this; } @Override public SpringAppDeploymentImpl withVersionName(String versionName) { ensureSource(); innerModel().properties().source().withVersion(versionName); return this; } @Override public SpringAppDeploymentImpl withActivation() { this.addPostRunDependent( context -> parent().update().withActiveDeployment(name()).applyAsync() .map(Function.identity()) ); return this; } @Override public Mono<SpringAppDeployment> createResourceAsync() { return manager().serviceClient().getDeployments().createOrUpdateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<SpringAppDeployment> updateResourceAsync() { return manager().serviceClient().getDeployments().updateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getDeployments().deleteAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override protected Mono<DeploymentResourceInner> getInnerAsync() { return manager().serviceClient().getDeployments().getAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String id() { return innerModel().id(); } @Override public SpringAppDeploymentImpl update() { prepareUpdate(); return this; } private AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl attach() { return parent().addActiveDeployment(this); } private SpringServiceImpl service() { return parent().parent(); } }
class SpringAppDeploymentImpl extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp> implements SpringAppDeployment, SpringAppDeployment.Definition<SpringAppImpl, SpringAppDeploymentImpl>, SpringAppDeployment.Update { SpringAppDeploymentImpl(String name, SpringAppImpl parent, DeploymentResourceInner innerObject) { super(name, parent, innerObject); } @Override public String appName() { if (innerModel().properties() == null) { return null; } return innerModel().name(); } @Override public DeploymentSettings settings() { if (innerModel().properties() == null) { return null; } return innerModel().properties().deploymentSettings(); } @Override public DeploymentResourceStatus status() { if (innerModel().properties() == null) { return null; } return innerModel().properties().status(); } @Override public boolean isActive() { if (innerModel().properties() == null) { return false; } return innerModel().properties().active(); } @Override public List<DeploymentInstance> instances() { if (innerModel().properties() == null) { return null; } return innerModel().properties().instances(); } @Override public void start() { startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().serviceClient().getDeployments().startAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void stop() { stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().serviceClient().getDeployments().stopAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void restart() { restartAsync().block(); } @Override public Mono<Void> restartAsync() { return manager().serviceClient().getDeployments().restartAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String getLogFileUrl() { return getLogFileUrlAsync().block(); } @Override public Mono<String> getLogFileUrlAsync() { return manager().serviceClient().getDeployments().getLogFileUrlAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ) .map(LogFileUrlResponseInner::url); } private void ensureDeploySettings() { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().deploymentSettings() == null) { innerModel().properties().withDeploymentSettings(new DeploymentSettings()); } } private void ensureSource() { ensureSource(null); } private void ensureSource(UserSourceType type) { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().source() == null) { if (type == UserSourceType.JAR) { innerModel().properties().withSource(new JarUploadedUserSourceInfo()); } else if (type == UserSourceType.SOURCE) { innerModel().properties().withSource(new SourceUploadedUserSourceInfo()); } else if (type == UserSourceType.NET_CORE_ZIP) { innerModel().properties().withSource(new NetCoreZipUploadedUserSourceInfo()); } else if (type == UserSourceType.BUILD_RESULT) { innerModel().properties().withSource(new BuildResultUserSourceInfo()); } else { innerModel().properties().withSource(new UserSourceInfo()); } } } private ShareFileAsyncClient createShareFileAsyncClient(ResourceUploadDefinition option) { return new ShareFileClientBuilder() .endpoint(option.uploadUrl()) .httpClient(manager().httpPipeline().getHttpClient()) .buildFileAsyncClient(); } private Mono<Void> uploadToStorage(File source, ResourceUploadDefinition option) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; try { uploadedUserSourceInfo.withRelativePath(option.relativePath()); ShareFileAsyncClient shareFileAsyncClient = createShareFileAsyncClient(option); return shareFileAsyncClient.create(source.length()) .flatMap(fileInfo -> shareFileAsyncClient.uploadFromFile(source.getAbsolutePath())) .then(Mono.empty()); } catch (Exception e) { return Mono.error(e); } } else { return Mono.empty(); } } @Override @Override public SpringAppDeploymentImpl withExistingSource(UserSourceType type, String relativePath) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); UserSourceInfo sourceInfo = innerModel().properties().source(); if (sourceInfo instanceof BuildResultUserSourceInfo) { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) sourceInfo; userSourceInfo.withBuildResultId(relativePath); } } else { ensureSource(type); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRelativePath(relativePath); } } return this; } private boolean isEnterpriseTier() { return service().isEnterpriseTier(); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz) { ensureSource(UserSourceType.SOURCE); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> uploadToStorage(sourceCodeTarGz, option) .then(context.voidMono())) ); return this; } @Override public SpringAppDeploymentImpl withTargetModule(String moduleName) { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(moduleName); } return this; } @Override public SpringAppDeploymentImpl withSingleModule() { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(null); } return this; } @Override public SpringAppDeploymentImpl withInstance(int count) { if (innerModel().sku() == null) { innerModel().withSku(parent().parent().sku()); } if (innerModel().sku() == null) { innerModel().withSku(new Sku().withName("B0")); } innerModel().sku().withCapacity(count); return this; } @Override public SpringAppDeploymentImpl withCpu(int cpuCount) { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } innerModel().properties().deploymentSettings().resourceRequests().withCpu(String.valueOf(cpuCount)); return this; } @Override public SpringAppDeploymentImpl withMemory(int sizeInGB) { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } innerModel().properties().deploymentSettings().resourceRequests().withMemory(String.format("%dGi", sizeInGB)); return this; } @Override public SpringAppDeploymentImpl withRuntime(RuntimeVersion version) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof NetCoreZipUploadedUserSourceInfo) { NetCoreZipUploadedUserSourceInfo uploadedUserSourceInfo = (NetCoreZipUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo uploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } return this; } @Override public SpringAppDeploymentImpl withJvmOptions(String jvmOptions) { ensureSource(UserSourceType.JAR); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withJvmOptions(jvmOptions); } return this; } private void ensureEnvironments() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().environmentVariables() == null) { innerModel().properties().deploymentSettings().withEnvironmentVariables(new HashMap<>()); } } @Override public SpringAppDeploymentImpl withEnvironment(String key, String value) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().put(key, value); return this; } @Override public SpringAppDeploymentImpl withoutEnvironment(String key) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().remove(key); return this; } @Override public SpringAppDeploymentImpl withVersionName(String versionName) { ensureSource(); innerModel().properties().source().withVersion(versionName); return this; } @Override public SpringAppDeploymentImpl withActivation() { this.addPostRunDependent( context -> parent().update().withActiveDeployment(name()).applyAsync() .map(Function.identity()) ); return this; } @Override public Mono<SpringAppDeployment> createResourceAsync() { return manager().serviceClient().getDeployments().createOrUpdateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<SpringAppDeployment> updateResourceAsync() { return manager().serviceClient().getDeployments().updateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getDeployments().deleteAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override protected Mono<DeploymentResourceInner> getInnerAsync() { return manager().serviceClient().getDeployments().getAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String id() { return innerModel().id(); } @Override public SpringAppDeploymentImpl update() { prepareUpdate(); return this; } private AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl attach() { return parent().addActiveDeployment(this); } private SpringServiceImpl service() { return parent().parent(); } }
So this `S1` etc. seems to be configurable in future PR? And for enterprise, does this mean it now had to send 2 PUT (or more if gitConfig set)?
public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); }
.withName("S1")))
public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private boolean updateConfigurationServiceTask = true; private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringConfigurationServices configurationServices() { return this.configurationServices; } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { if (isEnterpriseTier()) { return withGitConfig((ConfigurationServiceGitProperty) null); } else { return withGitConfig((ConfigServerGitProperty) null); } } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (updateConfigurationServiceTask) { prepareCreateOrUpdateConfigurationService(); } updateConfigurationServiceTask = false; } configServerTask = null; monitoringSettingTask = null; } @Override @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { clearCache(); if (isGroupFaulted) { return Mono.empty(); } return refreshAsync().then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withGitConfig(String uri, String branch, List<String> filePatterns) { return withGitConfigRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitConfigRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.gitRepositoryMap.computeIfAbsent(name, key -> new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch) ); updateConfigurationServiceTask = true; return this; } @Override public SpringServiceImpl withGitConfig(ConfigurationServiceGitProperty gitConfig) { gitRepositoryMap.clear(); if (gitConfig != null && CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.gitRepositoryMap.put(repository.name(), repository); } } updateConfigurationServiceTask = true; return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = new ArrayList<>(this.gitRepositoryMap.values()); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.gitRepositoryMap.clear(); this.configurationServices.clear(); } }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private final ConfigurationServiceConfig configurationServiceConfig = new ConfigurationServiceConfig(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { return withGitConfig(null); } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (isInCreateMode() || configurationServiceConfig.needUpdate()) { prepareCreateOrUpdateConfigurationService(); configurationServiceConfig.clearUpdate(); } } configServerTask = null; monitoringSettingTask = null; } @Override @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { return Mono .just(true) .map( ignored -> { clearCache(); return ignored; }) .then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withDefaultGitRepository(String uri, String branch, List<String> filePatterns) { return withGitRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.configurationServiceConfig.addRepository( new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch)); return this; } @Override public SpringServiceImpl withGitRepositoryConfig(ConfigurationServiceGitProperty gitConfig) { this.configurationServiceConfig.clearRepositories(); if (gitConfig != null && !CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.configurationServiceConfig.addRepository(repository); } } return this; } @Override public SpringServiceImpl withoutGitRepository(String name) { this.configurationServiceConfig.removeRepository(name); return this; } @Override public SpringServiceImpl withoutGitRepositories() { this.configurationServiceConfig.clearRepositories(); return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = this.configurationServiceConfig.mergeRepositories(); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.configurationServices.clear(); this.configurationServiceConfig.reset(); } private class ConfigurationServiceConfig { private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); private final Set<String> repositoriesToDelete = new HashSet<>(); private boolean update; private boolean clearRepositories; boolean needUpdate() { return update; } public void clearUpdate() { this.update = false; } void reset() { this.gitRepositoryMap.clear(); this.update = false; this.repositoriesToDelete.clear(); this.clearRepositories = false; } public void addRepository(ConfigurationServiceGitRepository repository) { this.gitRepositoryMap.putIfAbsent(repository.name(), repository); this.update = true; } public void clearRepositories() { this.gitRepositoryMap.clear(); this.clearRepositories = true; this.update = true; } public void removeRepository(String name) { this.repositoriesToDelete.add(name); this.update = true; } public List<ConfigurationServiceGitRepository> mergeRepositories() { if (this.clearRepositories) { return new ArrayList<>(this.gitRepositoryMap.values()); } else { Map<String, ConfigurationServiceGitRepository> existingGitRepositories = new HashMap<>(); if (isInUpdateMode()) { SpringConfigurationService configurationService = getDefaultConfigurationService(); if (configurationService != null) { List<ConfigurationServiceGitRepository> repositoryList = configurationService.innerModel().properties().settings() == null ? Collections.emptyList() : configurationService.innerModel().properties().settings().gitProperty().repositories(); if (repositoryList != null) { repositoryList.forEach(repository -> existingGitRepositories.put(repository.name(), repository)); } } } existingGitRepositories.putAll(gitRepositoryMap); for (String repositoryToDelete : repositoriesToDelete) { existingGitRepositories.remove(repositoryToDelete); } return new ArrayList<>(existingGitRepositories.values()); } } } }
It is configurable but I don't provide support for it. I can provide support in future PR. > And for enterprise, does this mean it now had to send 2 PUT (or more if gitConfig set)? Yes it does. Without this step, build service will not have a configured agent pool and future build will fail.. And for now, default `Configuration Service` will always be created regardless of whether git config is set as it's the default behavior of both portal and cli.
public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); }
.withName("S1")))
public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private boolean updateConfigurationServiceTask = true; private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringConfigurationServices configurationServices() { return this.configurationServices; } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { if (isEnterpriseTier()) { return withGitConfig((ConfigurationServiceGitProperty) null); } else { return withGitConfig((ConfigServerGitProperty) null); } } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (updateConfigurationServiceTask) { prepareCreateOrUpdateConfigurationService(); } updateConfigurationServiceTask = false; } configServerTask = null; monitoringSettingTask = null; } @Override @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { clearCache(); if (isGroupFaulted) { return Mono.empty(); } return refreshAsync().then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withGitConfig(String uri, String branch, List<String> filePatterns) { return withGitConfigRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitConfigRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.gitRepositoryMap.computeIfAbsent(name, key -> new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch) ); updateConfigurationServiceTask = true; return this; } @Override public SpringServiceImpl withGitConfig(ConfigurationServiceGitProperty gitConfig) { gitRepositoryMap.clear(); if (gitConfig != null && CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.gitRepositoryMap.put(repository.name(), repository); } } updateConfigurationServiceTask = true; return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = new ArrayList<>(this.gitRepositoryMap.values()); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.gitRepositoryMap.clear(); this.configurationServices.clear(); } }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private final ConfigurationServiceConfig configurationServiceConfig = new ConfigurationServiceConfig(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { return withGitConfig(null); } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (isInCreateMode() || configurationServiceConfig.needUpdate()) { prepareCreateOrUpdateConfigurationService(); configurationServiceConfig.clearUpdate(); } } configServerTask = null; monitoringSettingTask = null; } @Override @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { return Mono .just(true) .map( ignored -> { clearCache(); return ignored; }) .then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withDefaultGitRepository(String uri, String branch, List<String> filePatterns) { return withGitRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.configurationServiceConfig.addRepository( new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch)); return this; } @Override public SpringServiceImpl withGitRepositoryConfig(ConfigurationServiceGitProperty gitConfig) { this.configurationServiceConfig.clearRepositories(); if (gitConfig != null && !CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.configurationServiceConfig.addRepository(repository); } } return this; } @Override public SpringServiceImpl withoutGitRepository(String name) { this.configurationServiceConfig.removeRepository(name); return this; } @Override public SpringServiceImpl withoutGitRepositories() { this.configurationServiceConfig.clearRepositories(); return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = this.configurationServiceConfig.mergeRepositories(); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.configurationServices.clear(); this.configurationServiceConfig.reset(); } private class ConfigurationServiceConfig { private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); private final Set<String> repositoriesToDelete = new HashSet<>(); private boolean update; private boolean clearRepositories; boolean needUpdate() { return update; } public void clearUpdate() { this.update = false; } void reset() { this.gitRepositoryMap.clear(); this.update = false; this.repositoriesToDelete.clear(); this.clearRepositories = false; } public void addRepository(ConfigurationServiceGitRepository repository) { this.gitRepositoryMap.putIfAbsent(repository.name(), repository); this.update = true; } public void clearRepositories() { this.gitRepositoryMap.clear(); this.clearRepositories = true; this.update = true; } public void removeRepository(String name) { this.repositoriesToDelete.add(name); this.update = true; } public List<ConfigurationServiceGitRepository> mergeRepositories() { if (this.clearRepositories) { return new ArrayList<>(this.gitRepositoryMap.values()); } else { Map<String, ConfigurationServiceGitRepository> existingGitRepositories = new HashMap<>(); if (isInUpdateMode()) { SpringConfigurationService configurationService = getDefaultConfigurationService(); if (configurationService != null) { List<ConfigurationServiceGitRepository> repositoryList = configurationService.innerModel().properties().settings() == null ? Collections.emptyList() : configurationService.innerModel().properties().settings().gitProperty().repositories(); if (repositoryList != null) { repositoryList.forEach(repository -> existingGitRepositories.put(repository.name(), repository)); } } } existingGitRepositories.putAll(gitRepositoryMap); for (String repositoryToDelete : repositoriesToDelete) { existingGitRepositories.remove(repositoryToDelete); } return new ArrayList<>(existingGitRepositories.values()); } } } }
Yes, I'll add it.
private void clearCache() { this.gitRepositoryMap.clear(); this.configurationServices.clear(); }
this.configurationServices.clear();
private void clearCache() { this.configurationServices.clear(); this.configurationServiceConfig.reset(); }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private boolean updateConfigurationServiceTask = true; private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringConfigurationServices configurationServices() { return this.configurationServices; } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { if (isEnterpriseTier()) { return withGitConfig((ConfigurationServiceGitProperty) null); } else { return withGitConfig((ConfigServerGitProperty) null); } } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (updateConfigurationServiceTask) { prepareCreateOrUpdateConfigurationService(); } updateConfigurationServiceTask = false; } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { clearCache(); if (isGroupFaulted) { return Mono.empty(); } return refreshAsync().then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withGitConfig(String uri, String branch, List<String> filePatterns) { return withGitConfigRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitConfigRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.gitRepositoryMap.computeIfAbsent(name, key -> new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch) ); updateConfigurationServiceTask = true; return this; } @Override public SpringServiceImpl withGitConfig(ConfigurationServiceGitProperty gitConfig) { gitRepositoryMap.clear(); if (gitConfig != null && CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.gitRepositoryMap.put(repository.name(), repository); } } updateConfigurationServiceTask = true; return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = new ArrayList<>(this.gitRepositoryMap.values()); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private final ConfigurationServiceConfig configurationServiceConfig = new ConfigurationServiceConfig(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { return withGitConfig(null); } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (isInCreateMode() || configurationServiceConfig.needUpdate()) { prepareCreateOrUpdateConfigurationService(); configurationServiceConfig.clearUpdate(); } } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { return Mono .just(true) .map( ignored -> { clearCache(); return ignored; }) .then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withDefaultGitRepository(String uri, String branch, List<String> filePatterns) { return withGitRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.configurationServiceConfig.addRepository( new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch)); return this; } @Override public SpringServiceImpl withGitRepositoryConfig(ConfigurationServiceGitProperty gitConfig) { this.configurationServiceConfig.clearRepositories(); if (gitConfig != null && !CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.configurationServiceConfig.addRepository(repository); } } return this; } @Override public SpringServiceImpl withoutGitRepository(String name) { this.configurationServiceConfig.removeRepository(name); return this; } @Override public SpringServiceImpl withoutGitRepositories() { this.configurationServiceConfig.clearRepositories(); return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = this.configurationServiceConfig.mergeRepositories(); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private class ConfigurationServiceConfig { private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); private final Set<String> repositoriesToDelete = new HashSet<>(); private boolean update; private boolean clearRepositories; boolean needUpdate() { return update; } public void clearUpdate() { this.update = false; } void reset() { this.gitRepositoryMap.clear(); this.update = false; this.repositoriesToDelete.clear(); this.clearRepositories = false; } public void addRepository(ConfigurationServiceGitRepository repository) { this.gitRepositoryMap.putIfAbsent(repository.name(), repository); this.update = true; } public void clearRepositories() { this.gitRepositoryMap.clear(); this.clearRepositories = true; this.update = true; } public void removeRepository(String name) { this.repositoriesToDelete.add(name); this.update = true; } public List<ConfigurationServiceGitRepository> mergeRepositories() { if (this.clearRepositories) { return new ArrayList<>(this.gitRepositoryMap.values()); } else { Map<String, ConfigurationServiceGitRepository> existingGitRepositories = new HashMap<>(); if (isInUpdateMode()) { SpringConfigurationService configurationService = getDefaultConfigurationService(); if (configurationService != null) { List<ConfigurationServiceGitRepository> repositoryList = configurationService.innerModel().properties().settings() == null ? Collections.emptyList() : configurationService.innerModel().properties().settings().gitProperty().repositories(); if (repositoryList != null) { repositoryList.forEach(repository -> existingGitRepositories.put(repository.name(), repository)); } } } existingGitRepositories.putAll(gitRepositoryMap); for (String repositoryToDelete : repositoriesToDelete) { existingGitRepositories.remove(repositoryToDelete); } return new ArrayList<>(existingGitRepositories.values()); } } } }
Removed.
public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { clearCache(); if (isGroupFaulted) { return Mono.empty(); } return refreshAsync().then(); }
return refreshAsync().then();
public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { return Mono .just(true) .map( ignored -> { clearCache(); return ignored; }) .then(); }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private boolean updateConfigurationServiceTask = true; private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringConfigurationServices configurationServices() { return this.configurationServices; } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { if (isEnterpriseTier()) { return withGitConfig((ConfigurationServiceGitProperty) null); } else { return withGitConfig((ConfigServerGitProperty) null); } } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (updateConfigurationServiceTask) { prepareCreateOrUpdateConfigurationService(); } updateConfigurationServiceTask = false; } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withGitConfig(String uri, String branch, List<String> filePatterns) { return withGitConfigRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitConfigRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.gitRepositoryMap.computeIfAbsent(name, key -> new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch) ); updateConfigurationServiceTask = true; return this; } @Override public SpringServiceImpl withGitConfig(ConfigurationServiceGitProperty gitConfig) { gitRepositoryMap.clear(); if (gitConfig != null && CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.gitRepositoryMap.put(repository.name(), repository); } } updateConfigurationServiceTask = true; return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = new ArrayList<>(this.gitRepositoryMap.values()); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.gitRepositoryMap.clear(); this.configurationServices.clear(); } }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private final ConfigurationServiceConfig configurationServiceConfig = new ConfigurationServiceConfig(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutGitConfig() { return withGitConfig(null); } @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (isInCreateMode() || configurationServiceConfig.needUpdate()) { prepareCreateOrUpdateConfigurationService(); configurationServiceConfig.clearUpdate(); } } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withDefaultGitRepository(String uri, String branch, List<String> filePatterns) { return withGitRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.configurationServiceConfig.addRepository( new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch)); return this; } @Override public SpringServiceImpl withGitRepositoryConfig(ConfigurationServiceGitProperty gitConfig) { this.configurationServiceConfig.clearRepositories(); if (gitConfig != null && !CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.configurationServiceConfig.addRepository(repository); } } return this; } @Override public SpringServiceImpl withoutGitRepository(String name) { this.configurationServiceConfig.removeRepository(name); return this; } @Override public SpringServiceImpl withoutGitRepositories() { this.configurationServiceConfig.clearRepositories(); return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = this.configurationServiceConfig.mergeRepositories(); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.configurationServices.clear(); this.configurationServiceConfig.reset(); } private class ConfigurationServiceConfig { private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); private final Set<String> repositoriesToDelete = new HashSet<>(); private boolean update; private boolean clearRepositories; boolean needUpdate() { return update; } public void clearUpdate() { this.update = false; } void reset() { this.gitRepositoryMap.clear(); this.update = false; this.repositoriesToDelete.clear(); this.clearRepositories = false; } public void addRepository(ConfigurationServiceGitRepository repository) { this.gitRepositoryMap.putIfAbsent(repository.name(), repository); this.update = true; } public void clearRepositories() { this.gitRepositoryMap.clear(); this.clearRepositories = true; this.update = true; } public void removeRepository(String name) { this.repositoriesToDelete.add(name); this.update = true; } public List<ConfigurationServiceGitRepository> mergeRepositories() { if (this.clearRepositories) { return new ArrayList<>(this.gitRepositoryMap.values()); } else { Map<String, ConfigurationServiceGitRepository> existingGitRepositories = new HashMap<>(); if (isInUpdateMode()) { SpringConfigurationService configurationService = getDefaultConfigurationService(); if (configurationService != null) { List<ConfigurationServiceGitRepository> repositoryList = configurationService.innerModel().properties().settings() == null ? Collections.emptyList() : configurationService.innerModel().properties().settings().gitProperty().repositories(); if (repositoryList != null) { repositoryList.forEach(repository -> existingGitRepositories.put(repository.name(), repository)); } } } existingGitRepositories.putAll(gitRepositoryMap); for (String repositoryToDelete : repositoriesToDelete) { existingGitRepositories.remove(repositoryToDelete); } return new ArrayList<>(existingGitRepositories.values()); } } } }
Agree, I'm considering `withDefaultGitRepository()` and `withGitRepository()`. Will change it in next PR.
public SpringServiceImpl withoutGitConfig() { if (isEnterpriseTier()) { return withGitConfig((ConfigurationServiceGitProperty) null); } else { return withGitConfig((ConfigServerGitProperty) null); } }
return withGitConfig((ConfigServerGitProperty) null);
public SpringServiceImpl withoutGitConfig() { return withGitConfig(null); }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private boolean updateConfigurationServiceTask = true; private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringConfigurationServices configurationServices() { return this.configurationServices; } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (updateConfigurationServiceTask) { prepareCreateOrUpdateConfigurationService(); } updateConfigurationServiceTask = false; } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { clearCache(); if (isGroupFaulted) { return Mono.empty(); } return refreshAsync().then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withGitConfig(String uri, String branch, List<String> filePatterns) { return withGitConfigRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitConfigRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.gitRepositoryMap.computeIfAbsent(name, key -> new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch) ); updateConfigurationServiceTask = true; return this; } @Override public SpringServiceImpl withGitConfig(ConfigurationServiceGitProperty gitConfig) { gitRepositoryMap.clear(); if (gitConfig != null && CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.gitRepositoryMap.put(repository.name(), repository); } } updateConfigurationServiceTask = true; return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = new ArrayList<>(this.gitRepositoryMap.values()); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.gitRepositoryMap.clear(); this.configurationServices.clear(); } }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private final ConfigurationServiceConfig configurationServiceConfig = new ConfigurationServiceConfig(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (isInCreateMode() || configurationServiceConfig.needUpdate()) { prepareCreateOrUpdateConfigurationService(); configurationServiceConfig.clearUpdate(); } } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { return Mono .just(true) .map( ignored -> { clearCache(); return ignored; }) .then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withDefaultGitRepository(String uri, String branch, List<String> filePatterns) { return withGitRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.configurationServiceConfig.addRepository( new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch)); return this; } @Override public SpringServiceImpl withGitRepositoryConfig(ConfigurationServiceGitProperty gitConfig) { this.configurationServiceConfig.clearRepositories(); if (gitConfig != null && !CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.configurationServiceConfig.addRepository(repository); } } return this; } @Override public SpringServiceImpl withoutGitRepository(String name) { this.configurationServiceConfig.removeRepository(name); return this; } @Override public SpringServiceImpl withoutGitRepositories() { this.configurationServiceConfig.clearRepositories(); return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = this.configurationServiceConfig.mergeRepositories(); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.configurationServices.clear(); this.configurationServiceConfig.reset(); } private class ConfigurationServiceConfig { private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); private final Set<String> repositoriesToDelete = new HashSet<>(); private boolean update; private boolean clearRepositories; boolean needUpdate() { return update; } public void clearUpdate() { this.update = false; } void reset() { this.gitRepositoryMap.clear(); this.update = false; this.repositoriesToDelete.clear(); this.clearRepositories = false; } public void addRepository(ConfigurationServiceGitRepository repository) { this.gitRepositoryMap.putIfAbsent(repository.name(), repository); this.update = true; } public void clearRepositories() { this.gitRepositoryMap.clear(); this.clearRepositories = true; this.update = true; } public void removeRepository(String name) { this.repositoriesToDelete.add(name); this.update = true; } public List<ConfigurationServiceGitRepository> mergeRepositories() { if (this.clearRepositories) { return new ArrayList<>(this.gitRepositoryMap.values()); } else { Map<String, ConfigurationServiceGitRepository> existingGitRepositories = new HashMap<>(); if (isInUpdateMode()) { SpringConfigurationService configurationService = getDefaultConfigurationService(); if (configurationService != null) { List<ConfigurationServiceGitRepository> repositoryList = configurationService.innerModel().properties().settings() == null ? Collections.emptyList() : configurationService.innerModel().properties().settings().gitProperty().repositories(); if (repositoryList != null) { repositoryList.forEach(repository -> existingGitRepositories.put(repository.name(), repository)); } } } existingGitRepositories.putAll(gitRepositoryMap); for (String repositoryToDelete : repositoriesToDelete) { existingGitRepositories.remove(repositoryToDelete); } return new ArrayList<>(existingGitRepositories.values()); } } } }
remove the tailing `.`
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (!isKeyVaultClientOnClasspath()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "com.azure:azure-security-keyvault-secrets doesn't exist in classpath.")); return; } final AzureKeyVaultSecretProperties secretProperties = loadProperties(environment); if (!secretProperties.isPropertySourceEnabled()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-source-enabled=false")); return; } if (secretProperties.getPropertySources().isEmpty()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources is empty.")); return; } final List<AzureKeyVaultPropertySourceProperties> propertiesList = secretProperties.getPropertySources(); List<KeyVaultPropertySource> keyVaultPropertySources = buildKeyVaultPropertySourceList(propertiesList); final MutablePropertySources propertySources = environment.getPropertySources(); for (int i = keyVaultPropertySources.size() - 1; i >= 0; i--) { KeyVaultPropertySource propertySource = keyVaultPropertySources.get(i); logger.debug("Inserting Key Vault PropertySource. name = " + propertySource.getName()); if (propertySources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { propertySources.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertySource); } else { propertySources.addFirst(propertySource); } } }
logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "com.azure:azure-security-keyvault-secrets doesn't exist in classpath."));
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (!isKeyVaultClientOnClasspath()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "com.azure:azure-security-keyvault-secrets doesn't exist in classpath")); return; } final AzureKeyVaultSecretProperties secretProperties = loadProperties(environment); if (!secretProperties.isPropertySourceEnabled()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-source-enabled=false")); return; } if (secretProperties.getPropertySources().isEmpty()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources is empty")); return; } final List<AzureKeyVaultPropertySourceProperties> propertiesList = secretProperties.getPropertySources(); List<KeyVaultPropertySource> keyVaultPropertySources = buildKeyVaultPropertySourceList(propertiesList); final MutablePropertySources propertySources = environment.getPropertySources(); for (int i = keyVaultPropertySources.size() - 1; i >= 0; i--) { KeyVaultPropertySource propertySource = keyVaultPropertySources.get(i); logger.debug("Inserting Key Vault PropertySource. name = " + propertySource.getName()); if (propertySources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { propertySources.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertySource); } else { propertySources.addFirst(propertySource); } } }
class KeyVaultEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { public static final int ORDER = ConfigDataEnvironmentPostProcessor.ORDER + 1; private static final String SKIP_CONFIGURE_REASON_FORMAT = "Skip configuring Key Vault PropertySource because %s."; private final Log logger; /** * Creates a new instance of {@link KeyVaultEnvironmentPostProcessor}. * @param logger The logger used in this class. */ public KeyVaultEnvironmentPostProcessor(Log logger) { this.logger = logger; } /** * Construct a {@link KeyVaultEnvironmentPostProcessor} instance with a new {@link DeferredLog}. */ public KeyVaultEnvironmentPostProcessor() { this.logger = new DeferredLog(); } /** * Construct {@link KeyVaultPropertySource}s according to {@link AzureKeyVaultSecretProperties}, * then insert these {@link KeyVaultPropertySource}s into {@link ConfigurableEnvironment}. * * @param environment the environment. * @param application the application. */ @Override private List<KeyVaultPropertySource> buildKeyVaultPropertySourceList( List<AzureKeyVaultPropertySourceProperties> propertiesList) { List<KeyVaultPropertySource> propertySources = new ArrayList<>(); for (int i = 0; i < propertiesList.size(); i++) { AzureKeyVaultPropertySourceProperties properties = propertiesList.get(i); if (!properties.isEnabled()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources[" + i + "].enabled = false.")); continue; } if (!StringUtils.hasText(properties.getEndpoint())) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources[" + i + "].endpoint is empty.")); continue; } propertySources.add(buildKeyVaultPropertySource(properties)); } return propertySources; } private KeyVaultPropertySource buildKeyVaultPropertySource( AzureKeyVaultPropertySourceProperties properties) { try { final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( buildSecretClient(properties), properties.getRefreshInterval(), properties.getSecretKeys(), properties.isCaseSensitive()); return new KeyVaultPropertySource(properties.getName(), keyVaultOperation); } catch (final Exception exception) { throw new IllegalStateException("Failed to configure KeyVault property source", exception); } } private SecretClient buildSecretClient(AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultSecretProperties secretProperties = toAzureKeyVaultSecretProperties(propertySourceProperties); return buildSecretClient(secretProperties); } private AzureKeyVaultSecretProperties toAzureKeyVaultSecretProperties( AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultSecretProperties secretProperties = new AzureKeyVaultSecretProperties(); AzurePropertiesUtils.copyAzureCommonProperties(propertySourceProperties, secretProperties); secretProperties.setEndpoint(propertySourceProperties.getEndpoint()); secretProperties.setServiceVersion(propertySourceProperties.getServiceVersion()); return secretProperties; } /** * Build a KeyVault Secret client * @param secretProperties secret properties * @return secret client */ SecretClient buildSecretClient(AzureKeyVaultSecretProperties secretProperties) { return new SecretClientBuilderFactory(secretProperties).build().buildClient(); } AzureKeyVaultSecretProperties loadProperties(ConfigurableEnvironment environment) { Binder binder = Binder.get(environment); AzureGlobalProperties globalProperties = binder .bind(AzureGlobalProperties.PREFIX, Bindable.of(AzureGlobalProperties.class)) .orElseGet(AzureGlobalProperties::new); AzureKeyVaultSecretProperties secretProperties = binder .bind(AzureKeyVaultSecretProperties.PREFIX, Bindable.of(AzureKeyVaultSecretProperties.class)) .orElseGet(AzureKeyVaultSecretProperties::new); List<AzureKeyVaultPropertySourceProperties> list = secretProperties.getPropertySources(); for (int i = 0; i < list.size(); i++) { list.set(i, buildMergedProperties(globalProperties, list.get(i))); } for (int i = 0; i < list.size(); i++) { AzureKeyVaultPropertySourceProperties propertySourceProperties = list.get(i); if (!StringUtils.hasText(propertySourceProperties.getName())) { propertySourceProperties.setName(buildPropertySourceName(i)); } } return secretProperties; } private AzureKeyVaultPropertySourceProperties buildMergedProperties( AzureGlobalProperties globalProperties, AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultPropertySourceProperties mergedProperties = new AzureKeyVaultPropertySourceProperties(); AzurePropertiesUtils.mergeAzureCommonProperties(globalProperties, propertySourceProperties, mergedProperties); mergedProperties.setEnabled(propertySourceProperties.isEnabled()); mergedProperties.setName(propertySourceProperties.getName()); mergedProperties.setEndpoint(propertySourceProperties.getEndpoint()); mergedProperties.setServiceVersion(propertySourceProperties.getServiceVersion()); mergedProperties.setCaseSensitive(propertySourceProperties.isCaseSensitive()); mergedProperties.setSecretKeys(propertySourceProperties.getSecretKeys()); mergedProperties.setRefreshInterval(propertySourceProperties.getRefreshInterval()); return mergedProperties; } String buildPropertySourceName(int index) { return "azure-key-vault-secret-property-source-" + index; } private boolean isKeyVaultClientOnClasspath() { return ClassUtils.isPresent("com.azure.security.keyvault.secrets.SecretClient", KeyVaultEnvironmentPostProcessor.class.getClassLoader()); } /** * Get the order value of this object. * @return The order value. */ @Override public int getOrder() { return ORDER; } }
class KeyVaultEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { public static final int ORDER = ConfigDataEnvironmentPostProcessor.ORDER + 1; private static final String SKIP_CONFIGURE_REASON_FORMAT = "Skip configuring Key Vault PropertySource because %s."; private final Log logger; /** * Creates a new instance of {@link KeyVaultEnvironmentPostProcessor}. * @param logger The logger used in this class. */ public KeyVaultEnvironmentPostProcessor(Log logger) { this.logger = logger; } /** * Construct a {@link KeyVaultEnvironmentPostProcessor} instance with a new {@link DeferredLog}. */ public KeyVaultEnvironmentPostProcessor() { this.logger = new DeferredLog(); } /** * Construct {@link KeyVaultPropertySource}s according to {@link AzureKeyVaultSecretProperties}, * then insert these {@link KeyVaultPropertySource}s into {@link ConfigurableEnvironment}. * * @param environment the environment. * @param application the application. */ @Override private List<KeyVaultPropertySource> buildKeyVaultPropertySourceList( List<AzureKeyVaultPropertySourceProperties> propertiesList) { List<KeyVaultPropertySource> propertySources = new ArrayList<>(); for (int i = 0; i < propertiesList.size(); i++) { AzureKeyVaultPropertySourceProperties properties = propertiesList.get(i); if (!properties.isEnabled()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources[" + i + "].enabled = false")); continue; } if (!StringUtils.hasText(properties.getEndpoint())) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources[" + i + "].endpoint is empty")); continue; } propertySources.add(buildKeyVaultPropertySource(properties)); } return propertySources; } private KeyVaultPropertySource buildKeyVaultPropertySource( AzureKeyVaultPropertySourceProperties properties) { try { final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( buildSecretClient(properties), properties.getRefreshInterval(), properties.getSecretKeys(), properties.isCaseSensitive()); return new KeyVaultPropertySource(properties.getName(), keyVaultOperation); } catch (final Exception exception) { throw new IllegalStateException("Failed to configure KeyVault property source", exception); } } private SecretClient buildSecretClient(AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultSecretProperties secretProperties = toAzureKeyVaultSecretProperties(propertySourceProperties); return buildSecretClient(secretProperties); } private AzureKeyVaultSecretProperties toAzureKeyVaultSecretProperties( AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultSecretProperties secretProperties = new AzureKeyVaultSecretProperties(); AzurePropertiesUtils.copyAzureCommonProperties(propertySourceProperties, secretProperties); secretProperties.setEndpoint(propertySourceProperties.getEndpoint()); secretProperties.setServiceVersion(propertySourceProperties.getServiceVersion()); return secretProperties; } /** * Build a KeyVault Secret client * @param secretProperties secret properties * @return secret client */ SecretClient buildSecretClient(AzureKeyVaultSecretProperties secretProperties) { return new SecretClientBuilderFactory(secretProperties).build().buildClient(); } AzureKeyVaultSecretProperties loadProperties(ConfigurableEnvironment environment) { Binder binder = Binder.get(environment); AzureGlobalProperties globalProperties = binder .bind(AzureGlobalProperties.PREFIX, Bindable.of(AzureGlobalProperties.class)) .orElseGet(AzureGlobalProperties::new); AzureKeyVaultSecretProperties secretProperties = binder .bind(AzureKeyVaultSecretProperties.PREFIX, Bindable.of(AzureKeyVaultSecretProperties.class)) .orElseGet(AzureKeyVaultSecretProperties::new); List<AzureKeyVaultPropertySourceProperties> list = secretProperties.getPropertySources(); for (int i = 0; i < list.size(); i++) { list.set(i, buildMergedProperties(globalProperties, list.get(i))); } for (int i = 0; i < list.size(); i++) { AzureKeyVaultPropertySourceProperties propertySourceProperties = list.get(i); if (!StringUtils.hasText(propertySourceProperties.getName())) { propertySourceProperties.setName(buildPropertySourceName(i)); } } return secretProperties; } private AzureKeyVaultPropertySourceProperties buildMergedProperties( AzureGlobalProperties globalProperties, AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultPropertySourceProperties mergedProperties = new AzureKeyVaultPropertySourceProperties(); AzurePropertiesUtils.mergeAzureCommonProperties(globalProperties, propertySourceProperties, mergedProperties); mergedProperties.setEnabled(propertySourceProperties.isEnabled()); mergedProperties.setName(propertySourceProperties.getName()); mergedProperties.setEndpoint(propertySourceProperties.getEndpoint()); mergedProperties.setServiceVersion(propertySourceProperties.getServiceVersion()); mergedProperties.setCaseSensitive(propertySourceProperties.isCaseSensitive()); mergedProperties.setSecretKeys(propertySourceProperties.getSecretKeys()); mergedProperties.setRefreshInterval(propertySourceProperties.getRefreshInterval()); return mergedProperties; } String buildPropertySourceName(int index) { return "azure-key-vault-secret-property-source-" + index; } private boolean isKeyVaultClientOnClasspath() { return ClassUtils.isPresent("com.azure.security.keyvault.secrets.SecretClient", KeyVaultEnvironmentPostProcessor.class.getClassLoader()); } /** * Get the order value of this object. * @return The order value. */ @Override public int getOrder() { return ORDER; } }
same here
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (!isKeyVaultClientOnClasspath()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "com.azure:azure-security-keyvault-secrets doesn't exist in classpath.")); return; } final AzureKeyVaultSecretProperties secretProperties = loadProperties(environment); if (!secretProperties.isPropertySourceEnabled()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-source-enabled=false")); return; } if (secretProperties.getPropertySources().isEmpty()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources is empty.")); return; } final List<AzureKeyVaultPropertySourceProperties> propertiesList = secretProperties.getPropertySources(); List<KeyVaultPropertySource> keyVaultPropertySources = buildKeyVaultPropertySourceList(propertiesList); final MutablePropertySources propertySources = environment.getPropertySources(); for (int i = keyVaultPropertySources.size() - 1; i >= 0; i--) { KeyVaultPropertySource propertySource = keyVaultPropertySources.get(i); logger.debug("Inserting Key Vault PropertySource. name = " + propertySource.getName()); if (propertySources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { propertySources.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertySource); } else { propertySources.addFirst(propertySource); } } }
logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources is empty."));
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (!isKeyVaultClientOnClasspath()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "com.azure:azure-security-keyvault-secrets doesn't exist in classpath")); return; } final AzureKeyVaultSecretProperties secretProperties = loadProperties(environment); if (!secretProperties.isPropertySourceEnabled()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-source-enabled=false")); return; } if (secretProperties.getPropertySources().isEmpty()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources is empty")); return; } final List<AzureKeyVaultPropertySourceProperties> propertiesList = secretProperties.getPropertySources(); List<KeyVaultPropertySource> keyVaultPropertySources = buildKeyVaultPropertySourceList(propertiesList); final MutablePropertySources propertySources = environment.getPropertySources(); for (int i = keyVaultPropertySources.size() - 1; i >= 0; i--) { KeyVaultPropertySource propertySource = keyVaultPropertySources.get(i); logger.debug("Inserting Key Vault PropertySource. name = " + propertySource.getName()); if (propertySources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { propertySources.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertySource); } else { propertySources.addFirst(propertySource); } } }
class KeyVaultEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { public static final int ORDER = ConfigDataEnvironmentPostProcessor.ORDER + 1; private static final String SKIP_CONFIGURE_REASON_FORMAT = "Skip configuring Key Vault PropertySource because %s."; private final Log logger; /** * Creates a new instance of {@link KeyVaultEnvironmentPostProcessor}. * @param logger The logger used in this class. */ public KeyVaultEnvironmentPostProcessor(Log logger) { this.logger = logger; } /** * Construct a {@link KeyVaultEnvironmentPostProcessor} instance with a new {@link DeferredLog}. */ public KeyVaultEnvironmentPostProcessor() { this.logger = new DeferredLog(); } /** * Construct {@link KeyVaultPropertySource}s according to {@link AzureKeyVaultSecretProperties}, * then insert these {@link KeyVaultPropertySource}s into {@link ConfigurableEnvironment}. * * @param environment the environment. * @param application the application. */ @Override private List<KeyVaultPropertySource> buildKeyVaultPropertySourceList( List<AzureKeyVaultPropertySourceProperties> propertiesList) { List<KeyVaultPropertySource> propertySources = new ArrayList<>(); for (int i = 0; i < propertiesList.size(); i++) { AzureKeyVaultPropertySourceProperties properties = propertiesList.get(i); if (!properties.isEnabled()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources[" + i + "].enabled = false.")); continue; } if (!StringUtils.hasText(properties.getEndpoint())) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources[" + i + "].endpoint is empty.")); continue; } propertySources.add(buildKeyVaultPropertySource(properties)); } return propertySources; } private KeyVaultPropertySource buildKeyVaultPropertySource( AzureKeyVaultPropertySourceProperties properties) { try { final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( buildSecretClient(properties), properties.getRefreshInterval(), properties.getSecretKeys(), properties.isCaseSensitive()); return new KeyVaultPropertySource(properties.getName(), keyVaultOperation); } catch (final Exception exception) { throw new IllegalStateException("Failed to configure KeyVault property source", exception); } } private SecretClient buildSecretClient(AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultSecretProperties secretProperties = toAzureKeyVaultSecretProperties(propertySourceProperties); return buildSecretClient(secretProperties); } private AzureKeyVaultSecretProperties toAzureKeyVaultSecretProperties( AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultSecretProperties secretProperties = new AzureKeyVaultSecretProperties(); AzurePropertiesUtils.copyAzureCommonProperties(propertySourceProperties, secretProperties); secretProperties.setEndpoint(propertySourceProperties.getEndpoint()); secretProperties.setServiceVersion(propertySourceProperties.getServiceVersion()); return secretProperties; } /** * Build a KeyVault Secret client * @param secretProperties secret properties * @return secret client */ SecretClient buildSecretClient(AzureKeyVaultSecretProperties secretProperties) { return new SecretClientBuilderFactory(secretProperties).build().buildClient(); } AzureKeyVaultSecretProperties loadProperties(ConfigurableEnvironment environment) { Binder binder = Binder.get(environment); AzureGlobalProperties globalProperties = binder .bind(AzureGlobalProperties.PREFIX, Bindable.of(AzureGlobalProperties.class)) .orElseGet(AzureGlobalProperties::new); AzureKeyVaultSecretProperties secretProperties = binder .bind(AzureKeyVaultSecretProperties.PREFIX, Bindable.of(AzureKeyVaultSecretProperties.class)) .orElseGet(AzureKeyVaultSecretProperties::new); List<AzureKeyVaultPropertySourceProperties> list = secretProperties.getPropertySources(); for (int i = 0; i < list.size(); i++) { list.set(i, buildMergedProperties(globalProperties, list.get(i))); } for (int i = 0; i < list.size(); i++) { AzureKeyVaultPropertySourceProperties propertySourceProperties = list.get(i); if (!StringUtils.hasText(propertySourceProperties.getName())) { propertySourceProperties.setName(buildPropertySourceName(i)); } } return secretProperties; } private AzureKeyVaultPropertySourceProperties buildMergedProperties( AzureGlobalProperties globalProperties, AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultPropertySourceProperties mergedProperties = new AzureKeyVaultPropertySourceProperties(); AzurePropertiesUtils.mergeAzureCommonProperties(globalProperties, propertySourceProperties, mergedProperties); mergedProperties.setEnabled(propertySourceProperties.isEnabled()); mergedProperties.setName(propertySourceProperties.getName()); mergedProperties.setEndpoint(propertySourceProperties.getEndpoint()); mergedProperties.setServiceVersion(propertySourceProperties.getServiceVersion()); mergedProperties.setCaseSensitive(propertySourceProperties.isCaseSensitive()); mergedProperties.setSecretKeys(propertySourceProperties.getSecretKeys()); mergedProperties.setRefreshInterval(propertySourceProperties.getRefreshInterval()); return mergedProperties; } String buildPropertySourceName(int index) { return "azure-key-vault-secret-property-source-" + index; } private boolean isKeyVaultClientOnClasspath() { return ClassUtils.isPresent("com.azure.security.keyvault.secrets.SecretClient", KeyVaultEnvironmentPostProcessor.class.getClassLoader()); } /** * Get the order value of this object. * @return The order value. */ @Override public int getOrder() { return ORDER; } }
class KeyVaultEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { public static final int ORDER = ConfigDataEnvironmentPostProcessor.ORDER + 1; private static final String SKIP_CONFIGURE_REASON_FORMAT = "Skip configuring Key Vault PropertySource because %s."; private final Log logger; /** * Creates a new instance of {@link KeyVaultEnvironmentPostProcessor}. * @param logger The logger used in this class. */ public KeyVaultEnvironmentPostProcessor(Log logger) { this.logger = logger; } /** * Construct a {@link KeyVaultEnvironmentPostProcessor} instance with a new {@link DeferredLog}. */ public KeyVaultEnvironmentPostProcessor() { this.logger = new DeferredLog(); } /** * Construct {@link KeyVaultPropertySource}s according to {@link AzureKeyVaultSecretProperties}, * then insert these {@link KeyVaultPropertySource}s into {@link ConfigurableEnvironment}. * * @param environment the environment. * @param application the application. */ @Override private List<KeyVaultPropertySource> buildKeyVaultPropertySourceList( List<AzureKeyVaultPropertySourceProperties> propertiesList) { List<KeyVaultPropertySource> propertySources = new ArrayList<>(); for (int i = 0; i < propertiesList.size(); i++) { AzureKeyVaultPropertySourceProperties properties = propertiesList.get(i); if (!properties.isEnabled()) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources[" + i + "].enabled = false")); continue; } if (!StringUtils.hasText(properties.getEndpoint())) { logger.debug(String.format(SKIP_CONFIGURE_REASON_FORMAT, "spring.cloud.azure.keyvault.secret.property-sources[" + i + "].endpoint is empty")); continue; } propertySources.add(buildKeyVaultPropertySource(properties)); } return propertySources; } private KeyVaultPropertySource buildKeyVaultPropertySource( AzureKeyVaultPropertySourceProperties properties) { try { final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( buildSecretClient(properties), properties.getRefreshInterval(), properties.getSecretKeys(), properties.isCaseSensitive()); return new KeyVaultPropertySource(properties.getName(), keyVaultOperation); } catch (final Exception exception) { throw new IllegalStateException("Failed to configure KeyVault property source", exception); } } private SecretClient buildSecretClient(AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultSecretProperties secretProperties = toAzureKeyVaultSecretProperties(propertySourceProperties); return buildSecretClient(secretProperties); } private AzureKeyVaultSecretProperties toAzureKeyVaultSecretProperties( AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultSecretProperties secretProperties = new AzureKeyVaultSecretProperties(); AzurePropertiesUtils.copyAzureCommonProperties(propertySourceProperties, secretProperties); secretProperties.setEndpoint(propertySourceProperties.getEndpoint()); secretProperties.setServiceVersion(propertySourceProperties.getServiceVersion()); return secretProperties; } /** * Build a KeyVault Secret client * @param secretProperties secret properties * @return secret client */ SecretClient buildSecretClient(AzureKeyVaultSecretProperties secretProperties) { return new SecretClientBuilderFactory(secretProperties).build().buildClient(); } AzureKeyVaultSecretProperties loadProperties(ConfigurableEnvironment environment) { Binder binder = Binder.get(environment); AzureGlobalProperties globalProperties = binder .bind(AzureGlobalProperties.PREFIX, Bindable.of(AzureGlobalProperties.class)) .orElseGet(AzureGlobalProperties::new); AzureKeyVaultSecretProperties secretProperties = binder .bind(AzureKeyVaultSecretProperties.PREFIX, Bindable.of(AzureKeyVaultSecretProperties.class)) .orElseGet(AzureKeyVaultSecretProperties::new); List<AzureKeyVaultPropertySourceProperties> list = secretProperties.getPropertySources(); for (int i = 0; i < list.size(); i++) { list.set(i, buildMergedProperties(globalProperties, list.get(i))); } for (int i = 0; i < list.size(); i++) { AzureKeyVaultPropertySourceProperties propertySourceProperties = list.get(i); if (!StringUtils.hasText(propertySourceProperties.getName())) { propertySourceProperties.setName(buildPropertySourceName(i)); } } return secretProperties; } private AzureKeyVaultPropertySourceProperties buildMergedProperties( AzureGlobalProperties globalProperties, AzureKeyVaultPropertySourceProperties propertySourceProperties) { AzureKeyVaultPropertySourceProperties mergedProperties = new AzureKeyVaultPropertySourceProperties(); AzurePropertiesUtils.mergeAzureCommonProperties(globalProperties, propertySourceProperties, mergedProperties); mergedProperties.setEnabled(propertySourceProperties.isEnabled()); mergedProperties.setName(propertySourceProperties.getName()); mergedProperties.setEndpoint(propertySourceProperties.getEndpoint()); mergedProperties.setServiceVersion(propertySourceProperties.getServiceVersion()); mergedProperties.setCaseSensitive(propertySourceProperties.isCaseSensitive()); mergedProperties.setSecretKeys(propertySourceProperties.getSecretKeys()); mergedProperties.setRefreshInterval(propertySourceProperties.getRefreshInterval()); return mergedProperties; } String buildPropertySourceName(int index) { return "azure-key-vault-secret-property-source-" + index; } private boolean isKeyVaultClientOnClasspath() { return ClassUtils.isPresent("com.azure.security.keyvault.secrets.SecretClient", KeyVaultEnvironmentPostProcessor.class.getClassLoader()); } /** * Get the order value of this object. * @return The order value. */ @Override public int getOrder() { return ORDER; } }
TODO: all unknown properties should skipChildren, either the current token is a simple value like boolean, null, number, or string and this is a no-op and progression in the next loop will skip it. Or the value is pointing to a sub-object or array which will need to perform recursive skipping. There is a big question on how this will be handled when there is additional properties on the class.
public static SampleResource fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, (reader, token) -> { String namePropertiesName = null; String registrationTtl = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); token = reader.nextToken(); if ("properties".equals(fieldName) && token == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { namePropertiesName = reader.getStringValue(); } else if ("registrationTtl".equals(fieldName)) { registrationTtl = reader.getStringValue(); } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } return new SampleResource().withNamePropertiesName(namePropertiesName).withRegistrationTtl(registrationTtl); }); }
reader.skipChildren();
public static SampleResource fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, reader -> { String namePropertiesName = null; String registrationTtl = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("properties".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { namePropertiesName = reader.getStringValue(); } else if ("registrationTtl".equals(fieldName)) { registrationTtl = reader.getStringValue(); } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } return new SampleResource().withNamePropertiesName(namePropertiesName).withRegistrationTtl(registrationTtl); }); }
class SampleResource implements JsonCapable<SampleResource> { @JsonProperty(value = "properties.name") private String namePropertiesName; @JsonProperty(value = "properties.registrationTtl") private String registrationTtl; public SampleResource withNamePropertiesName(String namePropertiesName) { this.namePropertiesName = namePropertiesName; return this; } public SampleResource withRegistrationTtl(String registrationTtl) { this.registrationTtl = registrationTtl; return this; } public String getNamePropertiesName() { return namePropertiesName; } public String getRegistrationTtl() { return registrationTtl; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); if (namePropertiesName == null && registrationTtl == null) { return jsonWriter.writeEndObject().flush(); } jsonWriter.writeFieldName("properties").writeStartObject(); JsonUtils.writeNonNullStringField(jsonWriter, "name", namePropertiesName); JsonUtils.writeNonNullStringField(jsonWriter, "registrationTtl", registrationTtl); return jsonWriter.writeEndObject().writeEndObject().flush(); } }
class SampleResource implements JsonCapable<SampleResource> { private String namePropertiesName; private String registrationTtl; public SampleResource withNamePropertiesName(String namePropertiesName) { this.namePropertiesName = namePropertiesName; return this; } public SampleResource withRegistrationTtl(String registrationTtl) { this.registrationTtl = registrationTtl; return this; } public String getNamePropertiesName() { return namePropertiesName; } public String getRegistrationTtl() { return registrationTtl; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); if (namePropertiesName == null && registrationTtl == null) { return jsonWriter.writeEndObject().flush(); } jsonWriter.writeFieldName("properties").writeStartObject(); JsonUtils.writeNonNullStringField(jsonWriter, "name", namePropertiesName); JsonUtils.writeNonNullStringField(jsonWriter, "registrationTtl", registrationTtl); return jsonWriter.writeEndObject().writeEndObject().flush(); } }
for the future: would it make sense to add convenience on DefaultJsonWriter so it can hide stream manipulations? ```java DefaultJsonWriter writer = new DefaultJsonWriter(); toJson(writer); return writer.toString(); // can throw on the wrong state ```
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.toStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
toJson(writer);
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.fromStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, (reader, token) -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); token = jsonReader.nextToken(); switch (fieldName) { case "op": op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); break; case "from": from = jsonReader.getStringValue(); break; case "path": path = jsonReader.getStringValue(); break; case "value": if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { value = Option.of(jsonReader.readChildren()); } else if (token == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } break; default: break; } } return new JsonPatchOperation(op, from, path, value); }); } }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, reader -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); if ("op".equals(fieldName)) { op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); } else if ("from".equals(fieldName)) { from = jsonReader.getStringValue(); } else if ("path".equals(fieldName)) { path = jsonReader.getStringValue(); } else if ("value".equals(fieldName)) { if (reader.isStartArrayOrObject()) { value = Option.of(jsonReader.readChildren()); } else if (reader.currentToken() == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } } else { reader.skipChildren(); } } return new JsonPatchOperation(op, from, path, value); }); } }
is `toStream` name right? It feels `fromStream` is more intuitive
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.toStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
JsonWriter writer = DefaultJsonWriter.toStream(outputStream);
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.fromStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, (reader, token) -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); token = jsonReader.nextToken(); switch (fieldName) { case "op": op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); break; case "from": from = jsonReader.getStringValue(); break; case "path": path = jsonReader.getStringValue(); break; case "value": if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { value = Option.of(jsonReader.readChildren()); } else if (token == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } break; default: break; } } return new JsonPatchOperation(op, from, path, value); }); } }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, reader -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); if ("op".equals(fieldName)) { op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); } else if ("from".equals(fieldName)) { from = jsonReader.getStringValue(); } else if ("path".equals(fieldName)) { path = jsonReader.getStringValue(); } else if ("value".equals(fieldName)) { if (reader.isStartArrayOrObject()) { value = Option.of(jsonReader.readChildren()); } else if (reader.currentToken() == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } } else { reader.skipChildren(); } } return new JsonPatchOperation(op, from, path, value); }); } }
Why do we have explicit charset specified here?
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.toStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
return outputStream.toString(StandardCharsets.UTF_8);
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.fromStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, (reader, token) -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); token = jsonReader.nextToken(); switch (fieldName) { case "op": op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); break; case "from": from = jsonReader.getStringValue(); break; case "path": path = jsonReader.getStringValue(); break; case "value": if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { value = Option.of(jsonReader.readChildren()); } else if (token == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } break; default: break; } } return new JsonPatchOperation(op, from, path, value); }); } }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, reader -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); if ("op".equals(fieldName)) { op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); } else if ("from".equals(fieldName)) { from = jsonReader.getStringValue(); } else if ("path".equals(fieldName)) { path = jsonReader.getStringValue(); } else if ("value".equals(fieldName)) { if (reader.isStartArrayOrObject()) { value = Option.of(jsonReader.readChildren()); } else if (reader.currentToken() == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } } else { reader.skipChildren(); } } return new JsonPatchOperation(op, from, path, value); }); } }
Yeah, it reads a bit odd to have the `to` prefix. `from` may be more appropriate.
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.toStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
JsonWriter writer = DefaultJsonWriter.toStream(outputStream);
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.fromStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, (reader, token) -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); token = jsonReader.nextToken(); switch (fieldName) { case "op": op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); break; case "from": from = jsonReader.getStringValue(); break; case "path": path = jsonReader.getStringValue(); break; case "value": if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { value = Option.of(jsonReader.readChildren()); } else if (token == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } break; default: break; } } return new JsonPatchOperation(op, from, path, value); }); } }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, reader -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); if ("op".equals(fieldName)) { op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); } else if ("from".equals(fieldName)) { from = jsonReader.getStringValue(); } else if ("path".equals(fieldName)) { path = jsonReader.getStringValue(); } else if ("value".equals(fieldName)) { if (reader.isStartArrayOrObject()) { value = Option.of(jsonReader.readChildren()); } else if (reader.currentToken() == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } } else { reader.skipChildren(); } } return new JsonPatchOperation(op, from, path, value); }); } }
> && token == JsonToken.START_OBJECT what if it's not the case? It's the same concern as before on common place for validation + failure + logging and finding a pattern that would help models be consistent.
public static FlattenDangling fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, (reader, token) -> { String flattenedProperty = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); token = reader.nextToken(); if ("a".equals(fieldName) && token == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getStringValue(); token = reader.nextToken(); if ("flattened".equals(fieldName) && token == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getStringValue(); reader.nextToken(); if ("property".equals(fieldName)) { flattenedProperty = reader.getStringValue(); } } } } } } return new FlattenDangling().setFlattenedProperty(flattenedProperty); }); }
if ("a".equals(fieldName) && token == JsonToken.START_OBJECT) {
public static FlattenDangling fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, reader -> { FlattenDangling dangling = new FlattenDangling(); JsonUtils.readFields(reader, fieldName -> { if ("a".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { JsonUtils.readFields(reader, fieldName2 -> { if ("flattened".equals(fieldName2) && reader.currentToken() == JsonToken.START_OBJECT) { JsonUtils.readFields(reader, fieldName3 -> { if ("property".equals(fieldName3)) { dangling.setFlattenedProperty(reader.getStringValue()); } }); } }); } }); return dangling; }); }
class FlattenDangling implements JsonCapable<FlattenDangling> { @JsonProperty("a.flattened.property") @JsonFlatten private String flattenedProperty; public String getFlattenedProperty() { return flattenedProperty; } public FlattenDangling setFlattenedProperty(String flattenedProperty) { this.flattenedProperty = flattenedProperty; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); if (flattenedProperty != null) { jsonWriter.writeFieldName("a") .writeStartObject() .writeFieldName("flattened") .writeStartObject() .writeStringField("property", flattenedProperty) .writeEndObject() .writeEndObject(); } return jsonWriter.writeEndObject().flush(); } }
class FlattenDangling implements JsonCapable<FlattenDangling> { private String flattenedProperty; public String getFlattenedProperty() { return flattenedProperty; } public FlattenDangling setFlattenedProperty(String flattenedProperty) { this.flattenedProperty = flattenedProperty; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); if (flattenedProperty != null) { jsonWriter.writeFieldName("a") .writeStartObject() .writeFieldName("flattened") .writeStartObject() .writeStringField("property", flattenedProperty) .writeEndObject() .writeEndObject(); } return jsonWriter.writeEndObject().flush(); } }
this is the most difficult model I have ever seen :laughing:
public JsonWriter toJson(JsonWriter jsonWriter) { return null; }
return null;
public JsonWriter toJson(JsonWriter jsonWriter) { return toJsonInternal(jsonWriter, "foo"); }
class Foo implements JsonCapable<Foo> { @JsonProperty(value = "properties.bar") private String bar; @JsonProperty(value = "properties.props.baz") private List<String> baz; @JsonProperty(value = "properties.props.q.qux") private Map<String, String> qux; @JsonProperty(value = "properties.more\\.props") private String moreProps; @JsonProperty(value = "props.empty") private Integer empty; @JsonProperty(value = "") private Map<String, Object> additionalProperties; public String bar() { return bar; } public void bar(String bar) { this.bar = bar; } public List<String> baz() { return baz; } public void baz(List<String> baz) { this.baz = baz; } public Map<String, String> qux() { return qux; } public void qux(Map<String, String> qux) { this.qux = qux; } public String moreProps() { return moreProps; } public void moreProps(String moreProps) { this.moreProps = moreProps; } public Integer empty() { return empty; } public void empty(Integer empty) { this.empty = empty; } public Map<String, Object> additionalProperties() { return additionalProperties; } public void additionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; } @Override }
class Foo implements JsonCapable<Foo> { private String bar; private List<String> baz; private Map<String, String> qux; private String moreProps; private Integer empty; private Map<String, Object> additionalProperties; public String bar() { return bar; } public void bar(String bar) { this.bar = bar; } public List<String> baz() { return baz; } public void baz(List<String> baz) { this.baz = baz; } public Map<String, String> qux() { return qux; } public void qux(Map<String, String> qux) { this.qux = qux; } public String moreProps() { return moreProps; } public void moreProps(String moreProps) { this.moreProps = moreProps; } public Integer empty() { return empty; } public void empty(Integer empty) { this.empty = empty; } public Map<String, Object> additionalProperties() { return additionalProperties; } public void additionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; } @Override JsonWriter toJsonInternal(JsonWriter jsonWriter, String type) { jsonWriter.writeStartObject() .writeStringField("$type", type); if (bar != null || baz != null || qux != null || moreProps != null) { jsonWriter.writeFieldName("properties") .writeStartObject(); JsonUtils.writeNonNullStringField(jsonWriter, "bar", bar); if (baz != null || qux != null) { jsonWriter.writeFieldName("props") .writeStartObject(); if (baz != null) { JsonUtils.writeArray(jsonWriter, "baz", baz, JsonWriter::writeString); } if (qux != null) { jsonWriter.writeFieldName("q") .writeStartObject() .writeFieldName("qux") .writeStartObject(); qux.forEach(jsonWriter::writeStringField); jsonWriter.writeEndObject() .writeEndObject(); } jsonWriter.writeEndObject(); } JsonUtils.writeNonNullStringField(jsonWriter, "more.props", moreProps); jsonWriter.writeEndObject(); } if (empty != null) { jsonWriter.writeFieldName("props") .writeStartObject() .writeIntField("empty", empty) .writeEndObject(); } if (additionalProperties != null) { additionalProperties.forEach((key, value) -> JsonUtils.writeUntypedField(jsonWriter.writeFieldName(key), value)); } return jsonWriter.writeEndObject().flush(); } public static Foo fromJson(JsonReader jsonReader) { return fromJsonInternal(jsonReader, null); } static Foo fromJsonInternal(JsonReader jsonReader, String expectedType) { return JsonUtils.readObject(jsonReader, reader -> { String type = null; String bar = null; List<String> baz = null; Map<String, String> qux = null; String moreProps = null; Integer empty = null; Map<String, Object> additionalProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("$type".equals(fieldName)) { type = reader.getStringValue(); } else if ("properties".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("bar".equals(fieldName)) { bar = reader.getStringValue(); } else if ("more.props".equals(fieldName)) { moreProps = reader.getStringValue(); } else if ("props".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("baz".equals(fieldName)) { baz = JsonUtils.readArray(reader, r -> JsonUtils.getNullableProperty(r, JsonReader::getStringValue)); } else if ("q".equals(fieldName)) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("qux".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { if (qux == null) { qux = new LinkedHashMap<>(); } while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); qux.put(fieldName, JsonUtils.getNullableProperty(reader, JsonReader::getStringValue)); } } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } } else if ("props".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("empty".equals(fieldName)) { empty = reader.currentToken() == JsonToken.NULL ? null : reader.getIntValue(); } else { reader.skipChildren(); } } } else { if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); } additionalProperties.put(fieldName, JsonUtils.readUntypedField(reader)); } } if (expectedType != null && type != null && !Objects.equals(expectedType, type)) { throw new IllegalStateException("Discriminator field '$type' didn't match expected value: " + "'" + expectedType + "'. It was: '" + type + "'."); } if ((expectedType == null && type == null) || "foo".equals(type)) { Foo foo = new Foo(); foo.bar(bar); foo.baz(baz); foo.qux(qux); foo.moreProps(moreProps); foo.empty(empty); foo.additionalProperties(additionalProperties); return foo; } else if ("foochild".equals(expectedType) || "foochild".equals(type)) { FooChild fooChild = new FooChild(); fooChild.bar(bar); fooChild.baz(baz); fooChild.qux(qux); fooChild.moreProps(moreProps); fooChild.empty(empty); fooChild.additionalProperties(additionalProperties); return fooChild; } else { throw new IllegalStateException("Invalid discriminator value '" + reader.getStringValue() + "', expected: 'foo' or 'foochild'."); } }); } }
curious, are there valid cases like these where we have unknown property without additional properties. Would be great to write a warning there and eventually throw and try running integration tests to understand the scale of it.
public static SampleResource fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, (reader, token) -> { String namePropertiesName = null; String registrationTtl = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); token = reader.nextToken(); if ("properties".equals(fieldName) && token == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { namePropertiesName = reader.getStringValue(); } else if ("registrationTtl".equals(fieldName)) { registrationTtl = reader.getStringValue(); } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } return new SampleResource().withNamePropertiesName(namePropertiesName).withRegistrationTtl(registrationTtl); }); }
reader.skipChildren();
public static SampleResource fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, reader -> { String namePropertiesName = null; String registrationTtl = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("properties".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { namePropertiesName = reader.getStringValue(); } else if ("registrationTtl".equals(fieldName)) { registrationTtl = reader.getStringValue(); } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } return new SampleResource().withNamePropertiesName(namePropertiesName).withRegistrationTtl(registrationTtl); }); }
class SampleResource implements JsonCapable<SampleResource> { @JsonProperty(value = "properties.name") private String namePropertiesName; @JsonProperty(value = "properties.registrationTtl") private String registrationTtl; public SampleResource withNamePropertiesName(String namePropertiesName) { this.namePropertiesName = namePropertiesName; return this; } public SampleResource withRegistrationTtl(String registrationTtl) { this.registrationTtl = registrationTtl; return this; } public String getNamePropertiesName() { return namePropertiesName; } public String getRegistrationTtl() { return registrationTtl; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); if (namePropertiesName == null && registrationTtl == null) { return jsonWriter.writeEndObject().flush(); } jsonWriter.writeFieldName("properties").writeStartObject(); JsonUtils.writeNonNullStringField(jsonWriter, "name", namePropertiesName); JsonUtils.writeNonNullStringField(jsonWriter, "registrationTtl", registrationTtl); return jsonWriter.writeEndObject().writeEndObject().flush(); } }
class SampleResource implements JsonCapable<SampleResource> { private String namePropertiesName; private String registrationTtl; public SampleResource withNamePropertiesName(String namePropertiesName) { this.namePropertiesName = namePropertiesName; return this; } public SampleResource withRegistrationTtl(String registrationTtl) { this.registrationTtl = registrationTtl; return this; } public String getNamePropertiesName() { return namePropertiesName; } public String getRegistrationTtl() { return registrationTtl; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); if (namePropertiesName == null && registrationTtl == null) { return jsonWriter.writeEndObject().flush(); } jsonWriter.writeFieldName("properties").writeStartObject(); JsonUtils.writeNonNullStringField(jsonWriter, "name", namePropertiesName); JsonUtils.writeNonNullStringField(jsonWriter, "registrationTtl", registrationTtl); return jsonWriter.writeEndObject().writeEndObject().flush(); } }
> curious, are there valid cases like these where we have unknown property without additional properties. Would be great to write a warning there and eventually throw and try running integration tests to understand the scale of it. I believe this is possible and we can add a verbose level log to it
public static SampleResource fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, (reader, token) -> { String namePropertiesName = null; String registrationTtl = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); token = reader.nextToken(); if ("properties".equals(fieldName) && token == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { namePropertiesName = reader.getStringValue(); } else if ("registrationTtl".equals(fieldName)) { registrationTtl = reader.getStringValue(); } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } return new SampleResource().withNamePropertiesName(namePropertiesName).withRegistrationTtl(registrationTtl); }); }
reader.skipChildren();
public static SampleResource fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, reader -> { String namePropertiesName = null; String registrationTtl = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("properties".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { namePropertiesName = reader.getStringValue(); } else if ("registrationTtl".equals(fieldName)) { registrationTtl = reader.getStringValue(); } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } return new SampleResource().withNamePropertiesName(namePropertiesName).withRegistrationTtl(registrationTtl); }); }
class SampleResource implements JsonCapable<SampleResource> { @JsonProperty(value = "properties.name") private String namePropertiesName; @JsonProperty(value = "properties.registrationTtl") private String registrationTtl; public SampleResource withNamePropertiesName(String namePropertiesName) { this.namePropertiesName = namePropertiesName; return this; } public SampleResource withRegistrationTtl(String registrationTtl) { this.registrationTtl = registrationTtl; return this; } public String getNamePropertiesName() { return namePropertiesName; } public String getRegistrationTtl() { return registrationTtl; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); if (namePropertiesName == null && registrationTtl == null) { return jsonWriter.writeEndObject().flush(); } jsonWriter.writeFieldName("properties").writeStartObject(); JsonUtils.writeNonNullStringField(jsonWriter, "name", namePropertiesName); JsonUtils.writeNonNullStringField(jsonWriter, "registrationTtl", registrationTtl); return jsonWriter.writeEndObject().writeEndObject().flush(); } }
class SampleResource implements JsonCapable<SampleResource> { private String namePropertiesName; private String registrationTtl; public SampleResource withNamePropertiesName(String namePropertiesName) { this.namePropertiesName = namePropertiesName; return this; } public SampleResource withRegistrationTtl(String registrationTtl) { this.registrationTtl = registrationTtl; return this; } public String getNamePropertiesName() { return namePropertiesName; } public String getRegistrationTtl() { return registrationTtl; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); if (namePropertiesName == null && registrationTtl == null) { return jsonWriter.writeEndObject().flush(); } jsonWriter.writeFieldName("properties").writeStartObject(); JsonUtils.writeNonNullStringField(jsonWriter, "name", namePropertiesName); JsonUtils.writeNonNullStringField(jsonWriter, "registrationTtl", registrationTtl); return jsonWriter.writeEndObject().writeEndObject().flush(); } }
future concern: we probably want to limit the recursion depth here and in other helpers
public static Object readUntypedField(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == JsonToken.END_ARRAY || token == JsonToken.END_OBJECT || token == JsonToken.FIELD_NAME) { throw new IllegalStateException("Unexpected token to begin an untyped field: " + token); } if (token == JsonToken.NULL) { return null; } else if (token == JsonToken.BOOLEAN) { return jsonReader.getBooleanValue(); } else if (token == JsonToken.NUMBER) { String numberText = jsonReader.getTextValue(); if (numberText.contains(".")) { return Double.parseDouble(numberText); } else { return Long.parseLong(numberText); } } else if (token == JsonToken.STRING) { return jsonReader.getStringValue(); } else if (token == JsonToken.START_ARRAY) { List<Object> array = new ArrayList<>(); while (jsonReader.nextToken() != JsonToken.END_ARRAY) { array.add(readUntypedField(jsonReader)); } return array; } else if (token == JsonToken.START_OBJECT) { Map<String, Object> object = new LinkedHashMap<>(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); Object value = readUntypedField(jsonReader); object.put(fieldName, value); } return object; } throw new IllegalStateException("Unknown token type while reading an untyped field: " + token); }
Object value = readUntypedField(jsonReader);
public static Object readUntypedField(JsonReader jsonReader) { return readUntypedField(jsonReader, 0); }
class JsonUtils { /** * Serializes an array. * <p> * Handles three scenarios for the array: * * <ul> * <li>null {@code array} writes JSON null</li> * <li>empty {@code array} writes {@code []}</li> * <li>non-empty {@code array} writes a populated JSON array</li> * </ul> * * @param jsonWriter {@link JsonWriter} where JSON will be written. * @param fieldName Field name for the array. * @param array The array. * @param elementWriterFunc Function that writes the array element. * @param <T> Type of array element. * @return The updated {@link JsonWriter} object. */ public static <T> JsonWriter writeArray(JsonWriter jsonWriter, String fieldName, T[] array, BiConsumer<JsonWriter, T> elementWriterFunc) { jsonWriter.writeFieldName(fieldName); if (array == null) { return jsonWriter.writeNull().flush(); } jsonWriter.writeStartArray(); for (T element : array) { elementWriterFunc.accept(jsonWriter, element); } return jsonWriter.writeEndArray().flush(); } /** * Serializes an array. * <p> * Handles three scenarios for the array: * * <ul> * <li>null {@code array} writes JSON null</li> * <li>empty {@code array} writes {@code []}</li> * <li>non-empty {@code array} writes a populated JSON array</li> * </ul> * * @param jsonWriter {@link JsonWriter} where JSON will be written. * @param fieldName Field name for the array. * @param array The array. * @param elementWriterFunc Function that writes the array element. * @param <T> Type of array element. * @return The updated {@link JsonWriter} object. */ public static <T> JsonWriter writeArray(JsonWriter jsonWriter, String fieldName, Iterable<T> array, BiConsumer<JsonWriter, T> elementWriterFunc) { jsonWriter.writeFieldName(fieldName); if (array == null) { return jsonWriter.writeNull().flush(); } jsonWriter.writeStartArray(); for (T element : array) { elementWriterFunc.accept(jsonWriter, element); } return jsonWriter.writeEndArray().flush(); } /** * Handles basic logic for deserializing an object before passing it into the deserialization function. * <p> * This will initialize the {@link JsonReader} for object reading and then check if the current token is * {@link JsonToken * an {@link IllegalStateException}. The {@link JsonToken} passed into the {@code deserializationFunc} will be * {@link JsonToken * <p> * Use {@link * * @param jsonReader The {@link JsonReader} being read. * @param deserializationFunc The function that handles deserialization logic, passing the reader and current * token. * @param <T> The type of object that is being deserialized. * @return The deserialized object, or null if the {@link JsonToken * @throws IllegalStateException If the initial token for reading isn't {@link JsonToken */ public static <T> T readObject(JsonReader jsonReader, BiFunction<JsonReader, JsonToken, T> deserializationFunc) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } return deserializationFunc.apply(jsonReader, token); } /** * Handles basic logic for deserializing an array before passing it into the deserialization function. * <p> * This will initialize the {@link JsonReader} for array reading and then check if the current token is * {@link JsonToken * {@link IllegalStateException}. * <p> * Use {@link * * @param jsonReader The {@link JsonReader} being read. * @param deserializationFunc The function that handles deserialization logic. * @param <T> The type of array element that is being deserialized. * @return The deserialized array, or null if the {@link JsonToken * @throws IllegalStateException If the initial token for reading isn't {@link JsonToken */ public static <T> List<T> readArray(JsonReader jsonReader, BiFunction<JsonReader, JsonToken, T> deserializationFunc) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_ARRAY) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } List<T> array = new ArrayList<>(); while ((token = jsonReader.nextToken()) != JsonToken.END_ARRAY) { array.add(deserializationFunc.apply(jsonReader, token)); } return array; } /** * Writes the JSON string field if, and only if, {@code value} isn't null. * * @param writer The {@link JsonWriter} being written. * @param fieldName The field name. * @param value The value. * @return The updated {@link JsonWriter} if {@code value} wasn't null, otherwise the {@link JsonWriter} with no * modifications. */ public static JsonWriter writeNonNullStringField(JsonWriter writer, String fieldName, String value) { return (value == null) ? writer : writer.writeStringField(fieldName, value); } /** * Writes the JSON int field if, and only if, {@code value} isn't null. * * @param writer The {@link JsonWriter} being written. * @param fieldName The field name. * @param value The value. * @return The updated {@link JsonWriter} if {@code value} wasn't null, otherwise the {@link JsonWriter} with no * modifications. */ public static JsonWriter writeNonNullIntegerField(JsonWriter writer, String fieldName, Integer value) { return (value == null) ? writer : writer.writeIntField(fieldName, value); } /** * Reads the {@link JsonReader} as an untyped object. * <p> * The returned object is one of the following: * * <ul> * <li></li> * <li></li> * <li></li> * <li></li> * <li></li> * <li></li> * </ul> * * If the {@link JsonReader * {@link JsonToken * with the ending of an array or object or with the name of a field. * * @param jsonReader The {@link JsonReader} that will be read into an untyped object. * @return The untyped object based on the description. * @throws IllegalStateException If the {@link JsonReader * {@link JsonToken */ /** * Writes the {@code value} as an untyped field to the {@link JsonWriter}. * * @param jsonWriter The {@link JsonWriter} that will be written. * @param value The value to write. * @return The updated {@code jsonWriter} with the {@code value} written to it. */ public static JsonWriter writeUntypedField(JsonWriter jsonWriter, Object value) { if (value == null) { return jsonWriter.writeNull().flush(); } else if (value instanceof Short) { return jsonWriter.writeInt((short) value).flush(); } else if (value instanceof Integer) { return jsonWriter.writeInt((int) value).flush(); } else if (value instanceof Long) { return jsonWriter.writeLong((long) value).flush(); } else if (value instanceof Float) { return jsonWriter.writeFloat((float) value).flush(); } else if (value instanceof Double) { return jsonWriter.writeDouble((double) value).flush(); } else if (value instanceof Boolean) { return jsonWriter.writeBoolean((boolean) value).flush(); } else if (value instanceof byte[]) { return jsonWriter.writeBinary((byte[]) value).flush(); } else if (value instanceof CharSequence) { return jsonWriter.writeString(String.valueOf(value)).flush(); } else if (value instanceof JsonCapable<?>) { return ((JsonCapable<?>) value).toJson(jsonWriter).flush(); } else if (value.getClass() == Object.class) { return jsonWriter.writeStartObject().writeEndObject().flush(); } else { return jsonWriter.writeString(String.valueOf(value)).flush(); } } /** * Gets the nullable JSON property as null if the {@link JsonReader JsonReader's} {@link JsonReader * is {@link JsonToken * * @param jsonReader The {@link JsonReader} being read. * @param nonNullGetter The non-null getter. * @param <T> The type of the property. * @return Either null if the current token is {@link JsonToken * {@code nonNullGetter}. */ public static <T> T getNullableProperty(JsonReader jsonReader, Function<JsonReader, T> nonNullGetter) { return jsonReader.currentToken() == JsonToken.NULL ? null : nonNullGetter.apply(jsonReader); } private JsonUtils() { } }
class JsonUtils { /** * Serializes an array. * <p> * Handles three scenarios for the array: * * <ul> * <li>null {@code array} writes JSON null</li> * <li>empty {@code array} writes {@code []}</li> * <li>non-empty {@code array} writes a populated JSON array</li> * </ul> * * @param jsonWriter {@link JsonWriter} where JSON will be written. * @param fieldName Field name for the array. * @param array The array. * @param elementWriterFunc Function that writes the array element. * @param <T> Type of array element. * @return The updated {@link JsonWriter} object. */ public static <T> JsonWriter writeArray(JsonWriter jsonWriter, String fieldName, T[] array, BiConsumer<JsonWriter, T> elementWriterFunc) { jsonWriter.writeFieldName(fieldName); if (array == null) { return jsonWriter.writeNull().flush(); } jsonWriter.writeStartArray(); for (T element : array) { elementWriterFunc.accept(jsonWriter, element); } return jsonWriter.writeEndArray().flush(); } /** * Serializes an array. * <p> * Handles three scenarios for the array: * * <ul> * <li>null {@code array} writes JSON null</li> * <li>empty {@code array} writes {@code []}</li> * <li>non-empty {@code array} writes a populated JSON array</li> * </ul> * * @param jsonWriter {@link JsonWriter} where JSON will be written. * @param fieldName Field name for the array. * @param array The array. * @param elementWriterFunc Function that writes the array element. * @param <T> Type of array element. * @return The updated {@link JsonWriter} object. */ public static <T> JsonWriter writeArray(JsonWriter jsonWriter, String fieldName, Iterable<T> array, BiConsumer<JsonWriter, T> elementWriterFunc) { jsonWriter.writeFieldName(fieldName); if (array == null) { return jsonWriter.writeNull().flush(); } jsonWriter.writeStartArray(); for (T element : array) { elementWriterFunc.accept(jsonWriter, element); } return jsonWriter.writeEndArray().flush(); } /** * Handles basic logic for deserializing an object before passing it into the deserialization function. * <p> * This will initialize the {@link JsonReader} for object reading and then check if the current token is * {@link JsonToken * an {@link IllegalStateException}. The {@link JsonToken} passed into the {@code deserializationFunc} will be * {@link JsonToken * <p> * Use {@link * * @param jsonReader The {@link JsonReader} being read. * @param deserializationFunc The function that handles deserialization logic, passing the reader and current * token. * @param <T> The type of object that is being deserialized. * @return The deserialized object, or null if the {@link JsonToken * @throws IllegalStateException If the initial token for reading isn't {@link JsonToken */ public static <T> T readObject(JsonReader jsonReader, Function<JsonReader, T> deserializationFunc) { if (jsonReader.currentToken() == null) { jsonReader.nextToken(); } if (jsonReader.currentToken() == JsonToken.NULL) { return null; } else if (jsonReader.currentToken() != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + jsonReader.currentToken()); } return deserializationFunc.apply(jsonReader); } /** * Handles basic logic for deserializing an array before passing it into the deserialization function. * <p> * This will initialize the {@link JsonReader} for array reading and then check if the current token is * {@link JsonToken * {@link IllegalStateException}. * <p> * Use {@link * * @param jsonReader The {@link JsonReader} being read. * @param deserializationFunc The function that handles deserialization logic. * @param <T> The type of array element that is being deserialized. * @return The deserialized array, or null if the {@link JsonToken * @throws IllegalStateException If the initial token for reading isn't {@link JsonToken */ public static <T> List<T> readArray(JsonReader jsonReader, Function<JsonReader, T> deserializationFunc) { if (jsonReader.currentToken() == null) { jsonReader.nextToken(); } if (jsonReader.currentToken() == JsonToken.NULL) { return null; } else if (jsonReader.currentToken() != JsonToken.START_ARRAY) { throw new IllegalStateException("Unexpected token to begin deserialization: " + jsonReader.currentToken()); } List<T> array = new ArrayList<>(); while (jsonReader.nextToken() != JsonToken.END_ARRAY) { array.add(deserializationFunc.apply(jsonReader)); } return array; } /** * Writes the JSON string field if, and only if, {@code value} isn't null. * * @param writer The {@link JsonWriter} being written. * @param fieldName The field name. * @param value The value. * @return The updated {@link JsonWriter} if {@code value} wasn't null, otherwise the {@link JsonWriter} with no * modifications. */ public static JsonWriter writeNonNullStringField(JsonWriter writer, String fieldName, String value) { return (value == null) ? writer : writer.writeStringField(fieldName, value); } /** * Writes the JSON int field if, and only if, {@code value} isn't null. * * @param writer The {@link JsonWriter} being written. * @param fieldName The field name. * @param value The value. * @return The updated {@link JsonWriter} if {@code value} wasn't null, otherwise the {@link JsonWriter} with no * modifications. */ public static JsonWriter writeNonNullIntegerField(JsonWriter writer, String fieldName, Integer value) { return (value == null) ? writer : writer.writeIntField(fieldName, value); } /** * Reads the {@link JsonReader} as an untyped object. * <p> * The returned object is one of the following: * * <ul> * <li></li> * <li></li> * <li></li> * <li></li> * <li></li> * <li></li> * </ul> * * If the {@link JsonReader * {@link JsonToken * with the ending of an array or object or with the name of a field. * * @param jsonReader The {@link JsonReader} that will be read into an untyped object. * @return The untyped object based on the description. * @throws IllegalStateException If the {@link JsonReader * {@link JsonToken */ private static Object readUntypedField(JsonReader jsonReader, int depth) { if (depth >= 1000) { throw new IllegalStateException("Untyped object exceeded allowed object nested depth of 1000."); } JsonToken token = jsonReader.currentToken(); if (token == JsonToken.END_ARRAY || token == JsonToken.END_OBJECT || token == JsonToken.FIELD_NAME) { throw new IllegalStateException("Unexpected token to begin an untyped field: " + token); } if (token == JsonToken.NULL) { return null; } else if (token == JsonToken.BOOLEAN) { return jsonReader.getBooleanValue(); } else if (token == JsonToken.NUMBER) { String numberText = jsonReader.getTextValue(); if (numberText.contains(".")) { return Double.parseDouble(numberText); } else { return Long.parseLong(numberText); } } else if (token == JsonToken.STRING) { return jsonReader.getStringValue(); } else if (token == JsonToken.START_ARRAY) { List<Object> array = new ArrayList<>(); while (jsonReader.nextToken() != JsonToken.END_ARRAY) { array.add(readUntypedField(jsonReader, depth + 1)); } return array; } else if (token == JsonToken.START_OBJECT) { Map<String, Object> object = new LinkedHashMap<>(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); Object value = readUntypedField(jsonReader, depth + 1); object.put(fieldName, value); } return object; } throw new IllegalStateException("Unknown token type while reading an untyped field: " + token); } /** * Writes the {@code value} as an untyped field to the {@link JsonWriter}. * * @param jsonWriter The {@link JsonWriter} that will be written. * @param value The value to write. * @return The updated {@code jsonWriter} with the {@code value} written to it. */ public static JsonWriter writeUntypedField(JsonWriter jsonWriter, Object value) { if (value == null) { return jsonWriter.writeNull().flush(); } else if (value instanceof Short) { return jsonWriter.writeInt((short) value).flush(); } else if (value instanceof Integer) { return jsonWriter.writeInt((int) value).flush(); } else if (value instanceof Long) { return jsonWriter.writeLong((long) value).flush(); } else if (value instanceof Float) { return jsonWriter.writeFloat((float) value).flush(); } else if (value instanceof Double) { return jsonWriter.writeDouble((double) value).flush(); } else if (value instanceof Boolean) { return jsonWriter.writeBoolean((boolean) value).flush(); } else if (value instanceof byte[]) { return jsonWriter.writeBinary((byte[]) value).flush(); } else if (value instanceof CharSequence) { return jsonWriter.writeString(String.valueOf(value)).flush(); } else if (value instanceof JsonCapable<?>) { return ((JsonCapable<?>) value).toJson(jsonWriter).flush(); } else if (value.getClass() == Object.class) { return jsonWriter.writeStartObject().writeEndObject().flush(); } else { return jsonWriter.writeString(String.valueOf(value)).flush(); } } /** * Gets the nullable JSON property as null if the {@link JsonReader JsonReader's} {@link JsonReader * is {@link JsonToken * * @param jsonReader The {@link JsonReader} being read. * @param nonNullGetter The non-null getter. * @param <T> The type of the property. * @return Either null if the current token is {@link JsonToken * {@code nonNullGetter}. */ public static <T> T getNullableProperty(JsonReader jsonReader, Function<JsonReader, T> nonNullGetter) { return jsonReader.currentToken() == JsonToken.NULL ? null : nonNullGetter.apply(jsonReader); } /** * Reads the fields of a JSON object until the end of the object is reached. * <p> * The passed {@link JsonReader} will point to the field value each time {@code fieldNameConsumer} is called. * <p> * An {@link IllegalStateException} will be thrown if the {@link JsonReader * {@link JsonToken * * @param jsonReader The {@link JsonReader} being read. * @param fieldNameConsumer The field name consumer function. * @throws IllegalStateException If {@link JsonReader * {@link JsonToken */ public static void readFields(JsonReader jsonReader, Consumer<String> fieldNameConsumer) { readFields(jsonReader, false, fieldName -> { fieldNameConsumer.accept(fieldName); return false; }); } /** * Reads the fields of a JSON object until the end of the object is reached. * <p> * The passed {@link JsonReader} will point to the field value each time {@code fieldNameConsumer} is called. * <p> * An {@link IllegalStateException} will be thrown if the {@link JsonReader * {@link JsonToken * <p> * If {@code readAdditionalProperties} is true and {@code fieldNameConsumer} returns false the JSON field value * will be read as if it were an additional property. After the object completes reading the untyped additional * properties mapping will be returned, this may be null if there were no additional properties in the JSON object. * * @param jsonReader The {@link JsonReader} being read. * @param readAdditionalProperties Whether additional properties should be read. * @param fieldNameConsumer The field name consumer function. * @return The additional property map if {@code readAdditionalProperties} is true and there were additional * properties in the JSON object, otherwise null. * @throws IllegalStateException If {@link JsonReader * {@link JsonToken */ public static Map<String, Object> readFields(JsonReader jsonReader, boolean readAdditionalProperties, Function<String, Boolean> fieldNameConsumer) { if (jsonReader.currentToken() != JsonToken.START_OBJECT && jsonReader.currentToken() != JsonToken.NULL) { throw new IllegalStateException("Expected the current token of the JsonReader to either be " + "START_OBJECT or NULL. It was: " + jsonReader.currentToken()); } if (jsonReader.currentToken() == JsonToken.NULL) { return null; } Map<String, Object> additionalProperties = null; while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); boolean consumed = fieldNameConsumer.apply(fieldName); if (!consumed && readAdditionalProperties) { if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); } additionalProperties.put(fieldName, readUntypedField(jsonReader)); } else if (!consumed) { jsonReader.skipChildren(); } } return additionalProperties; } private JsonUtils() { } }
I've added the serialization and deserialization logic now 😄
public JsonWriter toJson(JsonWriter jsonWriter) { return null; }
return null;
public JsonWriter toJson(JsonWriter jsonWriter) { return toJsonInternal(jsonWriter, "foo"); }
class Foo implements JsonCapable<Foo> { @JsonProperty(value = "properties.bar") private String bar; @JsonProperty(value = "properties.props.baz") private List<String> baz; @JsonProperty(value = "properties.props.q.qux") private Map<String, String> qux; @JsonProperty(value = "properties.more\\.props") private String moreProps; @JsonProperty(value = "props.empty") private Integer empty; @JsonProperty(value = "") private Map<String, Object> additionalProperties; public String bar() { return bar; } public void bar(String bar) { this.bar = bar; } public List<String> baz() { return baz; } public void baz(List<String> baz) { this.baz = baz; } public Map<String, String> qux() { return qux; } public void qux(Map<String, String> qux) { this.qux = qux; } public String moreProps() { return moreProps; } public void moreProps(String moreProps) { this.moreProps = moreProps; } public Integer empty() { return empty; } public void empty(Integer empty) { this.empty = empty; } public Map<String, Object> additionalProperties() { return additionalProperties; } public void additionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; } @Override }
class Foo implements JsonCapable<Foo> { private String bar; private List<String> baz; private Map<String, String> qux; private String moreProps; private Integer empty; private Map<String, Object> additionalProperties; public String bar() { return bar; } public void bar(String bar) { this.bar = bar; } public List<String> baz() { return baz; } public void baz(List<String> baz) { this.baz = baz; } public Map<String, String> qux() { return qux; } public void qux(Map<String, String> qux) { this.qux = qux; } public String moreProps() { return moreProps; } public void moreProps(String moreProps) { this.moreProps = moreProps; } public Integer empty() { return empty; } public void empty(Integer empty) { this.empty = empty; } public Map<String, Object> additionalProperties() { return additionalProperties; } public void additionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; } @Override JsonWriter toJsonInternal(JsonWriter jsonWriter, String type) { jsonWriter.writeStartObject() .writeStringField("$type", type); if (bar != null || baz != null || qux != null || moreProps != null) { jsonWriter.writeFieldName("properties") .writeStartObject(); JsonUtils.writeNonNullStringField(jsonWriter, "bar", bar); if (baz != null || qux != null) { jsonWriter.writeFieldName("props") .writeStartObject(); if (baz != null) { JsonUtils.writeArray(jsonWriter, "baz", baz, JsonWriter::writeString); } if (qux != null) { jsonWriter.writeFieldName("q") .writeStartObject() .writeFieldName("qux") .writeStartObject(); qux.forEach(jsonWriter::writeStringField); jsonWriter.writeEndObject() .writeEndObject(); } jsonWriter.writeEndObject(); } JsonUtils.writeNonNullStringField(jsonWriter, "more.props", moreProps); jsonWriter.writeEndObject(); } if (empty != null) { jsonWriter.writeFieldName("props") .writeStartObject() .writeIntField("empty", empty) .writeEndObject(); } if (additionalProperties != null) { additionalProperties.forEach((key, value) -> JsonUtils.writeUntypedField(jsonWriter.writeFieldName(key), value)); } return jsonWriter.writeEndObject().flush(); } public static Foo fromJson(JsonReader jsonReader) { return fromJsonInternal(jsonReader, null); } static Foo fromJsonInternal(JsonReader jsonReader, String expectedType) { return JsonUtils.readObject(jsonReader, reader -> { String type = null; String bar = null; List<String> baz = null; Map<String, String> qux = null; String moreProps = null; Integer empty = null; Map<String, Object> additionalProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("$type".equals(fieldName)) { type = reader.getStringValue(); } else if ("properties".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("bar".equals(fieldName)) { bar = reader.getStringValue(); } else if ("more.props".equals(fieldName)) { moreProps = reader.getStringValue(); } else if ("props".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("baz".equals(fieldName)) { baz = JsonUtils.readArray(reader, r -> JsonUtils.getNullableProperty(r, JsonReader::getStringValue)); } else if ("q".equals(fieldName)) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("qux".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { if (qux == null) { qux = new LinkedHashMap<>(); } while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); qux.put(fieldName, JsonUtils.getNullableProperty(reader, JsonReader::getStringValue)); } } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } } else { reader.skipChildren(); } } } else if ("props".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { while (reader.nextToken() != JsonToken.END_OBJECT) { fieldName = reader.getFieldName(); reader.nextToken(); if ("empty".equals(fieldName)) { empty = reader.currentToken() == JsonToken.NULL ? null : reader.getIntValue(); } else { reader.skipChildren(); } } } else { if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); } additionalProperties.put(fieldName, JsonUtils.readUntypedField(reader)); } } if (expectedType != null && type != null && !Objects.equals(expectedType, type)) { throw new IllegalStateException("Discriminator field '$type' didn't match expected value: " + "'" + expectedType + "'. It was: '" + type + "'."); } if ((expectedType == null && type == null) || "foo".equals(type)) { Foo foo = new Foo(); foo.bar(bar); foo.baz(baz); foo.qux(qux); foo.moreProps(moreProps); foo.empty(empty); foo.additionalProperties(additionalProperties); return foo; } else if ("foochild".equals(expectedType) || "foochild".equals(type)) { FooChild fooChild = new FooChild(); fooChild.bar(bar); fooChild.baz(baz); fooChild.qux(qux); fooChild.moreProps(moreProps); fooChild.empty(empty); fooChild.additionalProperties(additionalProperties); return fooChild; } else { throw new IllegalStateException("Invalid discriminator value '" + reader.getStringValue() + "', expected: 'foo' or 'foochild'."); } }); } }
Added
public static Object readUntypedField(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == JsonToken.END_ARRAY || token == JsonToken.END_OBJECT || token == JsonToken.FIELD_NAME) { throw new IllegalStateException("Unexpected token to begin an untyped field: " + token); } if (token == JsonToken.NULL) { return null; } else if (token == JsonToken.BOOLEAN) { return jsonReader.getBooleanValue(); } else if (token == JsonToken.NUMBER) { String numberText = jsonReader.getTextValue(); if (numberText.contains(".")) { return Double.parseDouble(numberText); } else { return Long.parseLong(numberText); } } else if (token == JsonToken.STRING) { return jsonReader.getStringValue(); } else if (token == JsonToken.START_ARRAY) { List<Object> array = new ArrayList<>(); while (jsonReader.nextToken() != JsonToken.END_ARRAY) { array.add(readUntypedField(jsonReader)); } return array; } else if (token == JsonToken.START_OBJECT) { Map<String, Object> object = new LinkedHashMap<>(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); Object value = readUntypedField(jsonReader); object.put(fieldName, value); } return object; } throw new IllegalStateException("Unknown token type while reading an untyped field: " + token); }
Object value = readUntypedField(jsonReader);
public static Object readUntypedField(JsonReader jsonReader) { return readUntypedField(jsonReader, 0); }
class JsonUtils { /** * Serializes an array. * <p> * Handles three scenarios for the array: * * <ul> * <li>null {@code array} writes JSON null</li> * <li>empty {@code array} writes {@code []}</li> * <li>non-empty {@code array} writes a populated JSON array</li> * </ul> * * @param jsonWriter {@link JsonWriter} where JSON will be written. * @param fieldName Field name for the array. * @param array The array. * @param elementWriterFunc Function that writes the array element. * @param <T> Type of array element. * @return The updated {@link JsonWriter} object. */ public static <T> JsonWriter writeArray(JsonWriter jsonWriter, String fieldName, T[] array, BiConsumer<JsonWriter, T> elementWriterFunc) { jsonWriter.writeFieldName(fieldName); if (array == null) { return jsonWriter.writeNull().flush(); } jsonWriter.writeStartArray(); for (T element : array) { elementWriterFunc.accept(jsonWriter, element); } return jsonWriter.writeEndArray().flush(); } /** * Serializes an array. * <p> * Handles three scenarios for the array: * * <ul> * <li>null {@code array} writes JSON null</li> * <li>empty {@code array} writes {@code []}</li> * <li>non-empty {@code array} writes a populated JSON array</li> * </ul> * * @param jsonWriter {@link JsonWriter} where JSON will be written. * @param fieldName Field name for the array. * @param array The array. * @param elementWriterFunc Function that writes the array element. * @param <T> Type of array element. * @return The updated {@link JsonWriter} object. */ public static <T> JsonWriter writeArray(JsonWriter jsonWriter, String fieldName, Iterable<T> array, BiConsumer<JsonWriter, T> elementWriterFunc) { jsonWriter.writeFieldName(fieldName); if (array == null) { return jsonWriter.writeNull().flush(); } jsonWriter.writeStartArray(); for (T element : array) { elementWriterFunc.accept(jsonWriter, element); } return jsonWriter.writeEndArray().flush(); } /** * Handles basic logic for deserializing an object before passing it into the deserialization function. * <p> * This will initialize the {@link JsonReader} for object reading and then check if the current token is * {@link JsonToken * an {@link IllegalStateException}. The {@link JsonToken} passed into the {@code deserializationFunc} will be * {@link JsonToken * <p> * Use {@link * * @param jsonReader The {@link JsonReader} being read. * @param deserializationFunc The function that handles deserialization logic, passing the reader and current * token. * @param <T> The type of object that is being deserialized. * @return The deserialized object, or null if the {@link JsonToken * @throws IllegalStateException If the initial token for reading isn't {@link JsonToken */ public static <T> T readObject(JsonReader jsonReader, BiFunction<JsonReader, JsonToken, T> deserializationFunc) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } return deserializationFunc.apply(jsonReader, token); } /** * Handles basic logic for deserializing an array before passing it into the deserialization function. * <p> * This will initialize the {@link JsonReader} for array reading and then check if the current token is * {@link JsonToken * {@link IllegalStateException}. * <p> * Use {@link * * @param jsonReader The {@link JsonReader} being read. * @param deserializationFunc The function that handles deserialization logic. * @param <T> The type of array element that is being deserialized. * @return The deserialized array, or null if the {@link JsonToken * @throws IllegalStateException If the initial token for reading isn't {@link JsonToken */ public static <T> List<T> readArray(JsonReader jsonReader, BiFunction<JsonReader, JsonToken, T> deserializationFunc) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_ARRAY) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } List<T> array = new ArrayList<>(); while ((token = jsonReader.nextToken()) != JsonToken.END_ARRAY) { array.add(deserializationFunc.apply(jsonReader, token)); } return array; } /** * Writes the JSON string field if, and only if, {@code value} isn't null. * * @param writer The {@link JsonWriter} being written. * @param fieldName The field name. * @param value The value. * @return The updated {@link JsonWriter} if {@code value} wasn't null, otherwise the {@link JsonWriter} with no * modifications. */ public static JsonWriter writeNonNullStringField(JsonWriter writer, String fieldName, String value) { return (value == null) ? writer : writer.writeStringField(fieldName, value); } /** * Writes the JSON int field if, and only if, {@code value} isn't null. * * @param writer The {@link JsonWriter} being written. * @param fieldName The field name. * @param value The value. * @return The updated {@link JsonWriter} if {@code value} wasn't null, otherwise the {@link JsonWriter} with no * modifications. */ public static JsonWriter writeNonNullIntegerField(JsonWriter writer, String fieldName, Integer value) { return (value == null) ? writer : writer.writeIntField(fieldName, value); } /** * Reads the {@link JsonReader} as an untyped object. * <p> * The returned object is one of the following: * * <ul> * <li></li> * <li></li> * <li></li> * <li></li> * <li></li> * <li></li> * </ul> * * If the {@link JsonReader * {@link JsonToken * with the ending of an array or object or with the name of a field. * * @param jsonReader The {@link JsonReader} that will be read into an untyped object. * @return The untyped object based on the description. * @throws IllegalStateException If the {@link JsonReader * {@link JsonToken */ /** * Writes the {@code value} as an untyped field to the {@link JsonWriter}. * * @param jsonWriter The {@link JsonWriter} that will be written. * @param value The value to write. * @return The updated {@code jsonWriter} with the {@code value} written to it. */ public static JsonWriter writeUntypedField(JsonWriter jsonWriter, Object value) { if (value == null) { return jsonWriter.writeNull().flush(); } else if (value instanceof Short) { return jsonWriter.writeInt((short) value).flush(); } else if (value instanceof Integer) { return jsonWriter.writeInt((int) value).flush(); } else if (value instanceof Long) { return jsonWriter.writeLong((long) value).flush(); } else if (value instanceof Float) { return jsonWriter.writeFloat((float) value).flush(); } else if (value instanceof Double) { return jsonWriter.writeDouble((double) value).flush(); } else if (value instanceof Boolean) { return jsonWriter.writeBoolean((boolean) value).flush(); } else if (value instanceof byte[]) { return jsonWriter.writeBinary((byte[]) value).flush(); } else if (value instanceof CharSequence) { return jsonWriter.writeString(String.valueOf(value)).flush(); } else if (value instanceof JsonCapable<?>) { return ((JsonCapable<?>) value).toJson(jsonWriter).flush(); } else if (value.getClass() == Object.class) { return jsonWriter.writeStartObject().writeEndObject().flush(); } else { return jsonWriter.writeString(String.valueOf(value)).flush(); } } /** * Gets the nullable JSON property as null if the {@link JsonReader JsonReader's} {@link JsonReader * is {@link JsonToken * * @param jsonReader The {@link JsonReader} being read. * @param nonNullGetter The non-null getter. * @param <T> The type of the property. * @return Either null if the current token is {@link JsonToken * {@code nonNullGetter}. */ public static <T> T getNullableProperty(JsonReader jsonReader, Function<JsonReader, T> nonNullGetter) { return jsonReader.currentToken() == JsonToken.NULL ? null : nonNullGetter.apply(jsonReader); } private JsonUtils() { } }
class JsonUtils { /** * Serializes an array. * <p> * Handles three scenarios for the array: * * <ul> * <li>null {@code array} writes JSON null</li> * <li>empty {@code array} writes {@code []}</li> * <li>non-empty {@code array} writes a populated JSON array</li> * </ul> * * @param jsonWriter {@link JsonWriter} where JSON will be written. * @param fieldName Field name for the array. * @param array The array. * @param elementWriterFunc Function that writes the array element. * @param <T> Type of array element. * @return The updated {@link JsonWriter} object. */ public static <T> JsonWriter writeArray(JsonWriter jsonWriter, String fieldName, T[] array, BiConsumer<JsonWriter, T> elementWriterFunc) { jsonWriter.writeFieldName(fieldName); if (array == null) { return jsonWriter.writeNull().flush(); } jsonWriter.writeStartArray(); for (T element : array) { elementWriterFunc.accept(jsonWriter, element); } return jsonWriter.writeEndArray().flush(); } /** * Serializes an array. * <p> * Handles three scenarios for the array: * * <ul> * <li>null {@code array} writes JSON null</li> * <li>empty {@code array} writes {@code []}</li> * <li>non-empty {@code array} writes a populated JSON array</li> * </ul> * * @param jsonWriter {@link JsonWriter} where JSON will be written. * @param fieldName Field name for the array. * @param array The array. * @param elementWriterFunc Function that writes the array element. * @param <T> Type of array element. * @return The updated {@link JsonWriter} object. */ public static <T> JsonWriter writeArray(JsonWriter jsonWriter, String fieldName, Iterable<T> array, BiConsumer<JsonWriter, T> elementWriterFunc) { jsonWriter.writeFieldName(fieldName); if (array == null) { return jsonWriter.writeNull().flush(); } jsonWriter.writeStartArray(); for (T element : array) { elementWriterFunc.accept(jsonWriter, element); } return jsonWriter.writeEndArray().flush(); } /** * Handles basic logic for deserializing an object before passing it into the deserialization function. * <p> * This will initialize the {@link JsonReader} for object reading and then check if the current token is * {@link JsonToken * an {@link IllegalStateException}. The {@link JsonToken} passed into the {@code deserializationFunc} will be * {@link JsonToken * <p> * Use {@link * * @param jsonReader The {@link JsonReader} being read. * @param deserializationFunc The function that handles deserialization logic, passing the reader and current * token. * @param <T> The type of object that is being deserialized. * @return The deserialized object, or null if the {@link JsonToken * @throws IllegalStateException If the initial token for reading isn't {@link JsonToken */ public static <T> T readObject(JsonReader jsonReader, Function<JsonReader, T> deserializationFunc) { if (jsonReader.currentToken() == null) { jsonReader.nextToken(); } if (jsonReader.currentToken() == JsonToken.NULL) { return null; } else if (jsonReader.currentToken() != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + jsonReader.currentToken()); } return deserializationFunc.apply(jsonReader); } /** * Handles basic logic for deserializing an array before passing it into the deserialization function. * <p> * This will initialize the {@link JsonReader} for array reading and then check if the current token is * {@link JsonToken * {@link IllegalStateException}. * <p> * Use {@link * * @param jsonReader The {@link JsonReader} being read. * @param deserializationFunc The function that handles deserialization logic. * @param <T> The type of array element that is being deserialized. * @return The deserialized array, or null if the {@link JsonToken * @throws IllegalStateException If the initial token for reading isn't {@link JsonToken */ public static <T> List<T> readArray(JsonReader jsonReader, Function<JsonReader, T> deserializationFunc) { if (jsonReader.currentToken() == null) { jsonReader.nextToken(); } if (jsonReader.currentToken() == JsonToken.NULL) { return null; } else if (jsonReader.currentToken() != JsonToken.START_ARRAY) { throw new IllegalStateException("Unexpected token to begin deserialization: " + jsonReader.currentToken()); } List<T> array = new ArrayList<>(); while (jsonReader.nextToken() != JsonToken.END_ARRAY) { array.add(deserializationFunc.apply(jsonReader)); } return array; } /** * Writes the JSON string field if, and only if, {@code value} isn't null. * * @param writer The {@link JsonWriter} being written. * @param fieldName The field name. * @param value The value. * @return The updated {@link JsonWriter} if {@code value} wasn't null, otherwise the {@link JsonWriter} with no * modifications. */ public static JsonWriter writeNonNullStringField(JsonWriter writer, String fieldName, String value) { return (value == null) ? writer : writer.writeStringField(fieldName, value); } /** * Writes the JSON int field if, and only if, {@code value} isn't null. * * @param writer The {@link JsonWriter} being written. * @param fieldName The field name. * @param value The value. * @return The updated {@link JsonWriter} if {@code value} wasn't null, otherwise the {@link JsonWriter} with no * modifications. */ public static JsonWriter writeNonNullIntegerField(JsonWriter writer, String fieldName, Integer value) { return (value == null) ? writer : writer.writeIntField(fieldName, value); } /** * Reads the {@link JsonReader} as an untyped object. * <p> * The returned object is one of the following: * * <ul> * <li></li> * <li></li> * <li></li> * <li></li> * <li></li> * <li></li> * </ul> * * If the {@link JsonReader * {@link JsonToken * with the ending of an array or object or with the name of a field. * * @param jsonReader The {@link JsonReader} that will be read into an untyped object. * @return The untyped object based on the description. * @throws IllegalStateException If the {@link JsonReader * {@link JsonToken */ private static Object readUntypedField(JsonReader jsonReader, int depth) { if (depth >= 1000) { throw new IllegalStateException("Untyped object exceeded allowed object nested depth of 1000."); } JsonToken token = jsonReader.currentToken(); if (token == JsonToken.END_ARRAY || token == JsonToken.END_OBJECT || token == JsonToken.FIELD_NAME) { throw new IllegalStateException("Unexpected token to begin an untyped field: " + token); } if (token == JsonToken.NULL) { return null; } else if (token == JsonToken.BOOLEAN) { return jsonReader.getBooleanValue(); } else if (token == JsonToken.NUMBER) { String numberText = jsonReader.getTextValue(); if (numberText.contains(".")) { return Double.parseDouble(numberText); } else { return Long.parseLong(numberText); } } else if (token == JsonToken.STRING) { return jsonReader.getStringValue(); } else if (token == JsonToken.START_ARRAY) { List<Object> array = new ArrayList<>(); while (jsonReader.nextToken() != JsonToken.END_ARRAY) { array.add(readUntypedField(jsonReader, depth + 1)); } return array; } else if (token == JsonToken.START_OBJECT) { Map<String, Object> object = new LinkedHashMap<>(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); Object value = readUntypedField(jsonReader, depth + 1); object.put(fieldName, value); } return object; } throw new IllegalStateException("Unknown token type while reading an untyped field: " + token); } /** * Writes the {@code value} as an untyped field to the {@link JsonWriter}. * * @param jsonWriter The {@link JsonWriter} that will be written. * @param value The value to write. * @return The updated {@code jsonWriter} with the {@code value} written to it. */ public static JsonWriter writeUntypedField(JsonWriter jsonWriter, Object value) { if (value == null) { return jsonWriter.writeNull().flush(); } else if (value instanceof Short) { return jsonWriter.writeInt((short) value).flush(); } else if (value instanceof Integer) { return jsonWriter.writeInt((int) value).flush(); } else if (value instanceof Long) { return jsonWriter.writeLong((long) value).flush(); } else if (value instanceof Float) { return jsonWriter.writeFloat((float) value).flush(); } else if (value instanceof Double) { return jsonWriter.writeDouble((double) value).flush(); } else if (value instanceof Boolean) { return jsonWriter.writeBoolean((boolean) value).flush(); } else if (value instanceof byte[]) { return jsonWriter.writeBinary((byte[]) value).flush(); } else if (value instanceof CharSequence) { return jsonWriter.writeString(String.valueOf(value)).flush(); } else if (value instanceof JsonCapable<?>) { return ((JsonCapable<?>) value).toJson(jsonWriter).flush(); } else if (value.getClass() == Object.class) { return jsonWriter.writeStartObject().writeEndObject().flush(); } else { return jsonWriter.writeString(String.valueOf(value)).flush(); } } /** * Gets the nullable JSON property as null if the {@link JsonReader JsonReader's} {@link JsonReader * is {@link JsonToken * * @param jsonReader The {@link JsonReader} being read. * @param nonNullGetter The non-null getter. * @param <T> The type of the property. * @return Either null if the current token is {@link JsonToken * {@code nonNullGetter}. */ public static <T> T getNullableProperty(JsonReader jsonReader, Function<JsonReader, T> nonNullGetter) { return jsonReader.currentToken() == JsonToken.NULL ? null : nonNullGetter.apply(jsonReader); } /** * Reads the fields of a JSON object until the end of the object is reached. * <p> * The passed {@link JsonReader} will point to the field value each time {@code fieldNameConsumer} is called. * <p> * An {@link IllegalStateException} will be thrown if the {@link JsonReader * {@link JsonToken * * @param jsonReader The {@link JsonReader} being read. * @param fieldNameConsumer The field name consumer function. * @throws IllegalStateException If {@link JsonReader * {@link JsonToken */ public static void readFields(JsonReader jsonReader, Consumer<String> fieldNameConsumer) { readFields(jsonReader, false, fieldName -> { fieldNameConsumer.accept(fieldName); return false; }); } /** * Reads the fields of a JSON object until the end of the object is reached. * <p> * The passed {@link JsonReader} will point to the field value each time {@code fieldNameConsumer} is called. * <p> * An {@link IllegalStateException} will be thrown if the {@link JsonReader * {@link JsonToken * <p> * If {@code readAdditionalProperties} is true and {@code fieldNameConsumer} returns false the JSON field value * will be read as if it were an additional property. After the object completes reading the untyped additional * properties mapping will be returned, this may be null if there were no additional properties in the JSON object. * * @param jsonReader The {@link JsonReader} being read. * @param readAdditionalProperties Whether additional properties should be read. * @param fieldNameConsumer The field name consumer function. * @return The additional property map if {@code readAdditionalProperties} is true and there were additional * properties in the JSON object, otherwise null. * @throws IllegalStateException If {@link JsonReader * {@link JsonToken */ public static Map<String, Object> readFields(JsonReader jsonReader, boolean readAdditionalProperties, Function<String, Boolean> fieldNameConsumer) { if (jsonReader.currentToken() != JsonToken.START_OBJECT && jsonReader.currentToken() != JsonToken.NULL) { throw new IllegalStateException("Expected the current token of the JsonReader to either be " + "START_OBJECT or NULL. It was: " + jsonReader.currentToken()); } if (jsonReader.currentToken() == JsonToken.NULL) { return null; } Map<String, Object> additionalProperties = null; while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); boolean consumed = fieldNameConsumer.apply(fieldName); if (!consumed && readAdditionalProperties) { if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); } additionalProperties.put(fieldName, readUntypedField(jsonReader)); } else if (!consumed) { jsonReader.skipChildren(); } } return additionalProperties; } private JsonUtils() { } }
I chose `toStream` so it indicated that the JsonWriter was writing to the OutputStream, but I'm not sold on the naming either. This case is a bit harder given out common factory pattern of fromX but InputStream and OutputStream have a from/to connotation as well. For now, I'll change this to `fromStream` and we can discuss more when were closing to API complete.
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.toStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
JsonWriter writer = DefaultJsonWriter.toStream(outputStream);
public String toString() { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter writer = DefaultJsonWriter.fromStream(outputStream); toJson(writer); return outputStream.toString(StandardCharsets.UTF_8); }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, (reader, token) -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); token = jsonReader.nextToken(); switch (fieldName) { case "op": op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); break; case "from": from = jsonReader.getStringValue(); break; case "path": path = jsonReader.getStringValue(); break; case "value": if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { value = Option.of(jsonReader.readChildren()); } else if (token == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } break; default: break; } } return new JsonPatchOperation(op, from, path, value); }); } }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); } /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.readObject(jsonReader, reader -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); jsonReader.nextToken(); if ("op".equals(fieldName)) { op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); } else if ("from".equals(fieldName)) { from = jsonReader.getStringValue(); } else if ("path".equals(fieldName)) { path = jsonReader.getStringValue(); } else if ("value".equals(fieldName)) { if (reader.isStartArrayOrObject()) { value = Option.of(jsonReader.readChildren()); } else if (reader.currentToken() == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } } else { reader.skipChildren(); } } return new JsonPatchOperation(op, from, path, value); }); } }
unmodifiableList?
public List<String> configFilePatterns() { Map<String, Map<String, Object>> addonConfigs = this.innerModel().properties().deploymentSettings().addonConfigs(); if (addonConfigs == null) { return Collections.emptyList(); } Map<String, Object> configurationConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationConfigs == null) { return Collections.emptyList(); } String patterns = (String) configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY); if (CoreUtils.isNullOrEmpty(patterns)) { return Collections.emptyList(); } return Arrays.asList(patterns.split(",")); }
return Arrays.asList(patterns.split(","));
public List<String> configFilePatterns() { Map<String, Map<String, Object>> addonConfigs = this.innerModel().properties().deploymentSettings().addonConfigs(); if (addonConfigs == null) { return Collections.emptyList(); } Map<String, Object> configurationConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationConfigs == null) { return Collections.emptyList(); } if (configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY) instanceof String) { String patterns = (String) configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY); return Collections.unmodifiableList(Arrays.asList(patterns.split(","))); } else { return Collections.emptyList(); } }
class SpringAppDeploymentImpl extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp> implements SpringAppDeployment, SpringAppDeployment.Definition<SpringAppImpl, SpringAppDeploymentImpl>, SpringAppDeployment.Update { private BuildServiceTask buildServiceTask; SpringAppDeploymentImpl(String name, SpringAppImpl parent, DeploymentResourceInner innerObject) { super(name, parent, innerObject); } @Override public String appName() { if (innerModel().properties() == null) { return null; } return innerModel().name(); } @Override public DeploymentSettings settings() { if (innerModel().properties() == null) { return null; } return innerModel().properties().deploymentSettings(); } @Override public DeploymentResourceStatus status() { if (innerModel().properties() == null) { return null; } return innerModel().properties().status(); } @Override public boolean isActive() { if (innerModel().properties() == null) { return false; } return innerModel().properties().active(); } @Override public List<DeploymentInstance> instances() { if (innerModel().properties() == null) { return null; } return innerModel().properties().instances(); } @Override public void start() { startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().serviceClient().getDeployments().startAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void stop() { stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().serviceClient().getDeployments().stopAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void restart() { restartAsync().block(); } @Override public Mono<Void> restartAsync() { return manager().serviceClient().getDeployments().restartAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String getLogFileUrl() { return getLogFileUrlAsync().block(); } @Override public Mono<String> getLogFileUrlAsync() { return manager().serviceClient().getDeployments().getLogFileUrlAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ) .map(LogFileUrlResponseInner::url); } @Override private void ensureDeploySettings() { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().deploymentSettings() == null) { innerModel().properties().withDeploymentSettings(new DeploymentSettings()); } if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } } private void ensureSource() { ensureSource(null); } private void ensureSource(UserSourceType type) { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().source() == null) { if (type == UserSourceType.JAR) { innerModel().properties().withSource(new JarUploadedUserSourceInfo()); } else if (type == UserSourceType.SOURCE) { innerModel().properties().withSource(new SourceUploadedUserSourceInfo()); } else if (type == UserSourceType.NET_CORE_ZIP) { innerModel().properties().withSource(new NetCoreZipUploadedUserSourceInfo()); } else if (type == UserSourceType.BUILD_RESULT) { innerModel().properties().withSource(new BuildResultUserSourceInfo()); } else { innerModel().properties().withSource(new UserSourceInfo()); } } } @Override public SpringAppDeploymentImpl withJarFile(File jar) { if (service().isEnterpriseTier()) { return withJarFile(jar, null); } else { ensureSource(UserSourceType.JAR); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorage(jar, option) .then(context.voidMono()); }) ); return this; } } private ShareFileAsyncClient createShareFileAsyncClient(ResourceUploadDefinition option) { return new ShareFileClientBuilder() .endpoint(option.uploadUrl()) .httpClient(manager().httpPipeline().getHttpClient()) .buildFileAsyncClient(); } private Mono<Void> uploadToStorage(File source, ResourceUploadDefinition option) { try { ShareFileAsyncClient shareFileAsyncClient = createShareFileAsyncClient(option); return shareFileAsyncClient.create(source.length()) .flatMap(fileInfo -> shareFileAsyncClient.uploadFromFile(source.getAbsolutePath())) .then(Mono.empty()); } catch (Exception e) { return Mono.error(e); } } @Override public SpringAppDeploymentImpl withExistingSource(UserSourceType type, String relativePath) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); UserSourceInfo sourceInfo = innerModel().properties().source(); if (sourceInfo instanceof BuildResultUserSourceInfo) { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) sourceInfo; userSourceInfo.withBuildResultId(relativePath); } } else { ensureSource(type); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRelativePath(relativePath); } } return this; } @Override public SpringAppDeploymentImpl withJarFile(File jar, List<String> configFilePatterns) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(jar, configFilePatterns); return this; } private boolean isEnterpriseTier() { return service().isEnterpriseTier(); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz) { return withSourceCodeTarGzFile(sourceCodeTarGz, null); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz, List<String> configFilePatterns) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(sourceCodeTarGz, configFilePatterns, true); } else { ensureSource(UserSourceType.SOURCE); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorage(sourceCodeTarGz, option) .then(context.voidMono()); }) ); } return this; } @Override public SpringAppDeploymentImpl withTargetModule(String moduleName) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask.module = moduleName; } else { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(moduleName); } } return this; } @Override public SpringAppDeploymentImpl withSingleModule() { return withTargetModule(null); } @Override public SpringAppDeploymentImpl withInstance(int count) { if (innerModel().sku() == null) { innerModel().withSku(service().sku()); } if (innerModel().sku() == null) { innerModel().withSku(new Sku().withName("B0")); } innerModel().sku().withCapacity(count); return this; } @Override public SpringAppDeploymentImpl withCpu(int cpuCount) { return withCpu(String.valueOf(cpuCount)); } @Override public SpringAppDeploymentImpl withCpu(String cpuCount) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withCpu(cpuCount); return this; } @Override public SpringAppDeploymentImpl withMemory(int sizeInGB) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(String.format("%dGi", sizeInGB)); return this; } @Override public SpringAppDeploymentImpl withMemory(String size) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(size); return this; } @Override public SpringAppDeploymentImpl withRuntime(RuntimeVersion version) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof NetCoreZipUploadedUserSourceInfo) { NetCoreZipUploadedUserSourceInfo uploadedUserSourceInfo = (NetCoreZipUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo uploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } return this; } @Override public SpringAppDeploymentImpl withJvmOptions(String jvmOptions) { if (isEnterpriseTier()) { withEnvironment("JAVA_OPTS", jvmOptions); } else { ensureSource(UserSourceType.JAR); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withJvmOptions(jvmOptions); } } return this; } private void ensureEnvironments() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().environmentVariables() == null) { innerModel().properties().deploymentSettings().withEnvironmentVariables(new HashMap<>()); } } private void ensureAddonConfigs() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().addonConfigs() == null) { innerModel().properties().deploymentSettings().withAddonConfigs(new HashMap<>()); } } @Override public SpringAppDeploymentImpl withEnvironment(String key, String value) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().put(key, value); return this; } @Override public SpringAppDeploymentImpl withoutEnvironment(String key) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().remove(key); return this; } @Override public SpringAppDeploymentImpl withVersionName(String versionName) { ensureSource(); innerModel().properties().source().withVersion(versionName); return this; } @Override public SpringAppDeploymentImpl withActivation() { this.addPostRunDependent( context -> parent().update().withActiveDeployment(name()).applyAsync() .map(Function.identity()) ); return this; } @Override public SpringAppDeploymentImpl withConfigFilePatterns(List<String> configFilePatterns) { ensureAddonConfigs(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().deploymentSettings().addonConfigs(); addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, s -> { Map<String, Object> config = new HashMap<>(); config.put( Constants.CONFIG_FILE_PATTERNS_KEY, CoreUtils.isNullOrEmpty(configFilePatterns) ? "" : String.join(",", configFilePatterns)); return config; }); return this; } @Override public void beforeGroupCreateOrUpdate() { super.beforeGroupCreateOrUpdate(); if (this.buildServiceTask != null) { this.addDependency(this.buildServiceTask); this.buildServiceTask = null; } } @Override public Mono<SpringAppDeployment> createResourceAsync() { return manager().serviceClient().getDeployments().createOrUpdateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<SpringAppDeployment> updateResourceAsync() { return manager().serviceClient().getDeployments().updateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getDeployments().deleteAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override protected Mono<DeploymentResourceInner> getInnerAsync() { return manager().serviceClient().getDeployments().getAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String id() { return innerModel().id(); } @Override public SpringAppDeploymentImpl update() { prepareUpdate(); return this; } private AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl attach() { return parent().addActiveDeployment(this); } private SpringAppImpl app() { return parent(); } private SpringServiceImpl service() { return parent().parent(); } private class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuild(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> uploadAndBuild(File source, ResourceUploadDefinition option) { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return uploadToStorage(source, option) .then( new PollerFlux<>( manager().serviceClient().getDefaultPollInterval(), context -> enqueueBuild(option, context), this::waitForBuild, (pollResultPollingContext, pollResultPollResponse) -> Mono.error(new RuntimeException("build canceled")), this::getBuildResult) .last() .flatMap(client::getLroFinalResultOrError) .flatMap((Function<Object, Mono<String>>) o -> { BuildResultInner result = (BuildResultInner) o; return Mono.just(result.id()); }) ); } private Mono<BuildResultInner> getBuildResult(PollingContext<PollResult<BuildInner>> context) { return manager().serviceClient().getBuildServices() .getBuildResultAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(context.getData("buildId"))); } private Mono<PollResponse<PollResult<BuildInner>>> waitForBuild(PollingContext<PollResult<BuildInner>> context) { return getBuildResult(context) .flatMap((Function<BuildResultInner, Mono<PollResponse<PollResult<BuildInner>>>>) buildResultInner -> { BuildResultProvisioningState state = buildResultInner.properties().provisioningState(); PollResult<BuildInner> emptyResult = new PollResult<>(new BuildInner().withProperties(new BuildProperties())); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, emptyResult)); } else if (state == BuildResultProvisioningState.FAILED || state == BuildResultProvisioningState.DELETING) { return Mono.error(new RuntimeException("build failed")); } else if (state == BuildResultProvisioningState.QUEUING) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, emptyResult)); } return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, emptyResult)); }); } private Mono<PollResult<BuildInner>> enqueueBuild(ResourceUploadDefinition option, PollingContext<PollResult<BuildInner>> context) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> { context.setData("buildId", inner.properties().triggeredBuildResult().id()); return new PollResult<>(inner); }); } } }
class SpringAppDeploymentImpl extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp> implements SpringAppDeployment, SpringAppDeployment.Definition<SpringAppImpl, SpringAppDeploymentImpl>, SpringAppDeployment.Update { private static final Duration MAX_BUILD_TIMEOUT = Duration.ofHours(1); private BuildServiceTask buildServiceTask; SpringAppDeploymentImpl(String name, SpringAppImpl parent, DeploymentResourceInner innerObject) { super(name, parent, innerObject); } @Override public String appName() { if (innerModel().properties() == null) { return null; } return innerModel().name(); } @Override public DeploymentSettings settings() { if (innerModel().properties() == null) { return null; } return innerModel().properties().deploymentSettings(); } @Override public DeploymentResourceStatus status() { if (innerModel().properties() == null) { return null; } return innerModel().properties().status(); } @Override public boolean isActive() { if (innerModel().properties() == null) { return false; } return innerModel().properties().active(); } @Override public List<DeploymentInstance> instances() { if (innerModel().properties() == null) { return null; } return innerModel().properties().instances(); } @Override public void start() { startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().serviceClient().getDeployments().startAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void stop() { stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().serviceClient().getDeployments().stopAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void restart() { restartAsync().block(); } @Override public Mono<Void> restartAsync() { return manager().serviceClient().getDeployments().restartAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String getLogFileUrl() { return getLogFileUrlAsync().block(); } @Override public Mono<String> getLogFileUrlAsync() { return manager().serviceClient().getDeployments().getLogFileUrlAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ) .map(LogFileUrlResponseInner::url); } @Override private void ensureDeploySettings() { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().deploymentSettings() == null) { innerModel().properties().withDeploymentSettings(new DeploymentSettings()); } if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } } private void ensureSource() { ensureSource(null); } private void ensureSource(UserSourceType type) { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().source() == null) { if (type == UserSourceType.JAR) { innerModel().properties().withSource(new JarUploadedUserSourceInfo()); } else if (type == UserSourceType.SOURCE) { innerModel().properties().withSource(new SourceUploadedUserSourceInfo()); } else if (type == UserSourceType.NET_CORE_ZIP) { innerModel().properties().withSource(new NetCoreZipUploadedUserSourceInfo()); } else if (type == UserSourceType.BUILD_RESULT) { innerModel().properties().withSource(new BuildResultUserSourceInfo()); } else { innerModel().properties().withSource(new UserSourceInfo()); } } } @Override public SpringAppDeploymentImpl withJarFile(File jar) { if (service().isEnterpriseTier()) { return withJarFile(jar, null); } else { ensureSource(UserSourceType.JAR); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorageAsync(jar, option) .then(context.voidMono()); }) ); return this; } } private ShareFileAsyncClient createShareFileAsyncClient(ResourceUploadDefinition option) { return new ShareFileClientBuilder() .endpoint(option.uploadUrl()) .httpClient(manager().httpPipeline().getHttpClient()) .buildFileAsyncClient(); } private Mono<Void> uploadToStorageAsync(File source, ResourceUploadDefinition option) { try { ShareFileAsyncClient shareFileAsyncClient = createShareFileAsyncClient(option); return shareFileAsyncClient.create(source.length()) .flatMap(fileInfo -> shareFileAsyncClient.uploadFromFile(source.getAbsolutePath())) .then(Mono.empty()); } catch (Exception e) { return Mono.error(e); } } @Override public SpringAppDeploymentImpl withExistingSource(UserSourceType type, String relativePath) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); UserSourceInfo sourceInfo = innerModel().properties().source(); if (sourceInfo instanceof BuildResultUserSourceInfo) { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) sourceInfo; userSourceInfo.withBuildResultId(relativePath); } } else { ensureSource(type); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRelativePath(relativePath); } } return this; } @Override public SpringAppDeploymentImpl withJarFile(File jar, List<String> configFilePatterns) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(jar, configFilePatterns); return this; } private boolean isEnterpriseTier() { return service().isEnterpriseTier(); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz) { return withSourceCodeTarGzFile(sourceCodeTarGz, null); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz, List<String> configFilePatterns) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(sourceCodeTarGz, configFilePatterns, true); } else { ensureSource(UserSourceType.SOURCE); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorageAsync(sourceCodeTarGz, option) .then(context.voidMono()); }) ); } return this; } @Override public SpringAppDeploymentImpl withTargetModule(String moduleName) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask.module = moduleName; } else { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(moduleName); } } return this; } @Override public SpringAppDeploymentImpl withSingleModule() { return withTargetModule(null); } @Override public SpringAppDeploymentImpl withInstance(int count) { if (innerModel().sku() == null) { innerModel().withSku(service().sku()); } if (innerModel().sku() == null) { innerModel().withSku(new Sku().withName("B0")); } innerModel().sku().withCapacity(count); return this; } @Override public SpringAppDeploymentImpl withCpu(int cpuCount) { return withCpu(String.valueOf(cpuCount)); } @Override public SpringAppDeploymentImpl withCpu(String cpuCount) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withCpu(cpuCount); return this; } @Override public SpringAppDeploymentImpl withMemory(int sizeInGB) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(String.format("%dGi", sizeInGB)); return this; } @Override public SpringAppDeploymentImpl withMemory(String size) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(size); return this; } @Override public SpringAppDeploymentImpl withRuntime(RuntimeVersion version) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof NetCoreZipUploadedUserSourceInfo) { NetCoreZipUploadedUserSourceInfo uploadedUserSourceInfo = (NetCoreZipUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo uploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } return this; } @Override public SpringAppDeploymentImpl withJvmOptions(String jvmOptions) { if (isEnterpriseTier()) { withEnvironment("JAVA_OPTS", jvmOptions); } else { ensureSource(UserSourceType.JAR); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withJvmOptions(jvmOptions); } } return this; } private void ensureEnvironments() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().environmentVariables() == null) { innerModel().properties().deploymentSettings().withEnvironmentVariables(new HashMap<>()); } } private void ensureAddonConfigs() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().addonConfigs() == null) { innerModel().properties().deploymentSettings().withAddonConfigs(new HashMap<>()); } } @Override public SpringAppDeploymentImpl withEnvironment(String key, String value) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().put(key, value); return this; } @Override public SpringAppDeploymentImpl withoutEnvironment(String key) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().remove(key); return this; } @Override public SpringAppDeploymentImpl withVersionName(String versionName) { ensureSource(); innerModel().properties().source().withVersion(versionName); return this; } @Override public SpringAppDeploymentImpl withActivation() { this.addPostRunDependent( context -> parent().update().withActiveDeployment(name()).applyAsync() .map(Function.identity()) ); return this; } @Override public SpringAppDeploymentImpl withConfigFilePatterns(List<String> configFilePatterns) { ensureAddonConfigs(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().deploymentSettings().addonConfigs(); addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, s -> { Map<String, Object> config = new HashMap<>(); config.put( Constants.CONFIG_FILE_PATTERNS_KEY, CoreUtils.isNullOrEmpty(configFilePatterns) ? "" : String.join(",", configFilePatterns)); return config; }); return this; } @Override public void beforeGroupCreateOrUpdate() { super.beforeGroupCreateOrUpdate(); if (this.buildServiceTask != null) { this.addDependency(this.buildServiceTask); this.buildServiceTask = null; } } @Override public Mono<SpringAppDeployment> createResourceAsync() { return manager().serviceClient().getDeployments().createOrUpdateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<SpringAppDeployment> updateResourceAsync() { return manager().serviceClient().getDeployments().updateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getDeployments().deleteAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override protected Mono<DeploymentResourceInner> getInnerAsync() { return manager().serviceClient().getDeployments().getAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String id() { return innerModel().id(); } @Override public SpringAppDeploymentImpl update() { prepareUpdate(); return this; } private AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl attach() { return parent().addActiveDeployment(this); } private SpringAppImpl app() { return parent(); } private SpringServiceImpl service() { return parent().parent(); } private class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { AtomicLong pollCount = new AtomicLong(); Duration pollDuration = manager().serviceClient().getDefaultPollInterval(); return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultWithResponseAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(response -> { if (pollDuration.multipliedBy(pollCount.get()).compareTo(MAX_BUILD_TIMEOUT) < 0) { BuildResultProvisioningState state = response.getValue().properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return Mono.error(new ManagementException(String.format("Build failed for file: %s, buildId: %s", file.getName(), buildId), new HttpResponseImpl<>(response, client.getSerializerAdapter()))); } } else { return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", file.getName(), buildId), null)); } }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> { pollCount.set(index); return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); }))); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } @SuppressWarnings("BlockingMethodInNonBlockingContext") private class HttpResponseImpl<T> extends HttpResponse { private final Response<T> response; private final SerializerAdapter serializerAdapter; protected HttpResponseImpl(Response<T> response, SerializerAdapter serializerAdapter) { super(response.getRequest()); this.response = response; this.serializerAdapter = serializerAdapter; } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public String getHeaderValue(String header) { return response.getHeaders().getValue(header); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { try { return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } } @Override public Mono<byte[]> getBodyAsByteArray() { try { return Mono.just(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON)); } catch (IOException e) { return Mono.empty(); } } @Override public Mono<String> getBodyAsString() { return Mono.just(serializerAdapter.serializeRaw(response.getValue())); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsString(); } } } }
Protection on type=String
public List<String> configFilePatterns() { Map<String, Map<String, Object>> addonConfigs = this.innerModel().properties().deploymentSettings().addonConfigs(); if (addonConfigs == null) { return Collections.emptyList(); } Map<String, Object> configurationConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationConfigs == null) { return Collections.emptyList(); } String patterns = (String) configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY); if (CoreUtils.isNullOrEmpty(patterns)) { return Collections.emptyList(); } return Arrays.asList(patterns.split(",")); }
String patterns = (String) configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY);
public List<String> configFilePatterns() { Map<String, Map<String, Object>> addonConfigs = this.innerModel().properties().deploymentSettings().addonConfigs(); if (addonConfigs == null) { return Collections.emptyList(); } Map<String, Object> configurationConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationConfigs == null) { return Collections.emptyList(); } if (configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY) instanceof String) { String patterns = (String) configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY); return Collections.unmodifiableList(Arrays.asList(patterns.split(","))); } else { return Collections.emptyList(); } }
class SpringAppDeploymentImpl extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp> implements SpringAppDeployment, SpringAppDeployment.Definition<SpringAppImpl, SpringAppDeploymentImpl>, SpringAppDeployment.Update { private BuildServiceTask buildServiceTask; SpringAppDeploymentImpl(String name, SpringAppImpl parent, DeploymentResourceInner innerObject) { super(name, parent, innerObject); } @Override public String appName() { if (innerModel().properties() == null) { return null; } return innerModel().name(); } @Override public DeploymentSettings settings() { if (innerModel().properties() == null) { return null; } return innerModel().properties().deploymentSettings(); } @Override public DeploymentResourceStatus status() { if (innerModel().properties() == null) { return null; } return innerModel().properties().status(); } @Override public boolean isActive() { if (innerModel().properties() == null) { return false; } return innerModel().properties().active(); } @Override public List<DeploymentInstance> instances() { if (innerModel().properties() == null) { return null; } return innerModel().properties().instances(); } @Override public void start() { startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().serviceClient().getDeployments().startAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void stop() { stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().serviceClient().getDeployments().stopAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void restart() { restartAsync().block(); } @Override public Mono<Void> restartAsync() { return manager().serviceClient().getDeployments().restartAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String getLogFileUrl() { return getLogFileUrlAsync().block(); } @Override public Mono<String> getLogFileUrlAsync() { return manager().serviceClient().getDeployments().getLogFileUrlAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ) .map(LogFileUrlResponseInner::url); } @Override private void ensureDeploySettings() { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().deploymentSettings() == null) { innerModel().properties().withDeploymentSettings(new DeploymentSettings()); } if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } } private void ensureSource() { ensureSource(null); } private void ensureSource(UserSourceType type) { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().source() == null) { if (type == UserSourceType.JAR) { innerModel().properties().withSource(new JarUploadedUserSourceInfo()); } else if (type == UserSourceType.SOURCE) { innerModel().properties().withSource(new SourceUploadedUserSourceInfo()); } else if (type == UserSourceType.NET_CORE_ZIP) { innerModel().properties().withSource(new NetCoreZipUploadedUserSourceInfo()); } else if (type == UserSourceType.BUILD_RESULT) { innerModel().properties().withSource(new BuildResultUserSourceInfo()); } else { innerModel().properties().withSource(new UserSourceInfo()); } } } @Override public SpringAppDeploymentImpl withJarFile(File jar) { if (service().isEnterpriseTier()) { return withJarFile(jar, null); } else { ensureSource(UserSourceType.JAR); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorage(jar, option) .then(context.voidMono()); }) ); return this; } } private ShareFileAsyncClient createShareFileAsyncClient(ResourceUploadDefinition option) { return new ShareFileClientBuilder() .endpoint(option.uploadUrl()) .httpClient(manager().httpPipeline().getHttpClient()) .buildFileAsyncClient(); } private Mono<Void> uploadToStorage(File source, ResourceUploadDefinition option) { try { ShareFileAsyncClient shareFileAsyncClient = createShareFileAsyncClient(option); return shareFileAsyncClient.create(source.length()) .flatMap(fileInfo -> shareFileAsyncClient.uploadFromFile(source.getAbsolutePath())) .then(Mono.empty()); } catch (Exception e) { return Mono.error(e); } } @Override public SpringAppDeploymentImpl withExistingSource(UserSourceType type, String relativePath) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); UserSourceInfo sourceInfo = innerModel().properties().source(); if (sourceInfo instanceof BuildResultUserSourceInfo) { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) sourceInfo; userSourceInfo.withBuildResultId(relativePath); } } else { ensureSource(type); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRelativePath(relativePath); } } return this; } @Override public SpringAppDeploymentImpl withJarFile(File jar, List<String> configFilePatterns) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(jar, configFilePatterns); return this; } private boolean isEnterpriseTier() { return service().isEnterpriseTier(); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz) { return withSourceCodeTarGzFile(sourceCodeTarGz, null); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz, List<String> configFilePatterns) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(sourceCodeTarGz, configFilePatterns, true); } else { ensureSource(UserSourceType.SOURCE); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorage(sourceCodeTarGz, option) .then(context.voidMono()); }) ); } return this; } @Override public SpringAppDeploymentImpl withTargetModule(String moduleName) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask.module = moduleName; } else { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(moduleName); } } return this; } @Override public SpringAppDeploymentImpl withSingleModule() { return withTargetModule(null); } @Override public SpringAppDeploymentImpl withInstance(int count) { if (innerModel().sku() == null) { innerModel().withSku(service().sku()); } if (innerModel().sku() == null) { innerModel().withSku(new Sku().withName("B0")); } innerModel().sku().withCapacity(count); return this; } @Override public SpringAppDeploymentImpl withCpu(int cpuCount) { return withCpu(String.valueOf(cpuCount)); } @Override public SpringAppDeploymentImpl withCpu(String cpuCount) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withCpu(cpuCount); return this; } @Override public SpringAppDeploymentImpl withMemory(int sizeInGB) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(String.format("%dGi", sizeInGB)); return this; } @Override public SpringAppDeploymentImpl withMemory(String size) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(size); return this; } @Override public SpringAppDeploymentImpl withRuntime(RuntimeVersion version) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof NetCoreZipUploadedUserSourceInfo) { NetCoreZipUploadedUserSourceInfo uploadedUserSourceInfo = (NetCoreZipUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo uploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } return this; } @Override public SpringAppDeploymentImpl withJvmOptions(String jvmOptions) { if (isEnterpriseTier()) { withEnvironment("JAVA_OPTS", jvmOptions); } else { ensureSource(UserSourceType.JAR); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withJvmOptions(jvmOptions); } } return this; } private void ensureEnvironments() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().environmentVariables() == null) { innerModel().properties().deploymentSettings().withEnvironmentVariables(new HashMap<>()); } } private void ensureAddonConfigs() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().addonConfigs() == null) { innerModel().properties().deploymentSettings().withAddonConfigs(new HashMap<>()); } } @Override public SpringAppDeploymentImpl withEnvironment(String key, String value) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().put(key, value); return this; } @Override public SpringAppDeploymentImpl withoutEnvironment(String key) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().remove(key); return this; } @Override public SpringAppDeploymentImpl withVersionName(String versionName) { ensureSource(); innerModel().properties().source().withVersion(versionName); return this; } @Override public SpringAppDeploymentImpl withActivation() { this.addPostRunDependent( context -> parent().update().withActiveDeployment(name()).applyAsync() .map(Function.identity()) ); return this; } @Override public SpringAppDeploymentImpl withConfigFilePatterns(List<String> configFilePatterns) { ensureAddonConfigs(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().deploymentSettings().addonConfigs(); addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, s -> { Map<String, Object> config = new HashMap<>(); config.put( Constants.CONFIG_FILE_PATTERNS_KEY, CoreUtils.isNullOrEmpty(configFilePatterns) ? "" : String.join(",", configFilePatterns)); return config; }); return this; } @Override public void beforeGroupCreateOrUpdate() { super.beforeGroupCreateOrUpdate(); if (this.buildServiceTask != null) { this.addDependency(this.buildServiceTask); this.buildServiceTask = null; } } @Override public Mono<SpringAppDeployment> createResourceAsync() { return manager().serviceClient().getDeployments().createOrUpdateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<SpringAppDeployment> updateResourceAsync() { return manager().serviceClient().getDeployments().updateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getDeployments().deleteAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override protected Mono<DeploymentResourceInner> getInnerAsync() { return manager().serviceClient().getDeployments().getAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String id() { return innerModel().id(); } @Override public SpringAppDeploymentImpl update() { prepareUpdate(); return this; } private AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl attach() { return parent().addActiveDeployment(this); } private SpringAppImpl app() { return parent(); } private SpringServiceImpl service() { return parent().parent(); } private class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuild(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> uploadAndBuild(File source, ResourceUploadDefinition option) { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return uploadToStorage(source, option) .then( new PollerFlux<>( manager().serviceClient().getDefaultPollInterval(), context -> enqueueBuild(option, context), this::waitForBuild, (pollResultPollingContext, pollResultPollResponse) -> Mono.error(new RuntimeException("build canceled")), this::getBuildResult) .last() .flatMap(client::getLroFinalResultOrError) .flatMap((Function<Object, Mono<String>>) o -> { BuildResultInner result = (BuildResultInner) o; return Mono.just(result.id()); }) ); } private Mono<BuildResultInner> getBuildResult(PollingContext<PollResult<BuildInner>> context) { return manager().serviceClient().getBuildServices() .getBuildResultAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(context.getData("buildId"))); } private Mono<PollResponse<PollResult<BuildInner>>> waitForBuild(PollingContext<PollResult<BuildInner>> context) { return getBuildResult(context) .flatMap((Function<BuildResultInner, Mono<PollResponse<PollResult<BuildInner>>>>) buildResultInner -> { BuildResultProvisioningState state = buildResultInner.properties().provisioningState(); PollResult<BuildInner> emptyResult = new PollResult<>(new BuildInner().withProperties(new BuildProperties())); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, emptyResult)); } else if (state == BuildResultProvisioningState.FAILED || state == BuildResultProvisioningState.DELETING) { return Mono.error(new RuntimeException("build failed")); } else if (state == BuildResultProvisioningState.QUEUING) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, emptyResult)); } return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, emptyResult)); }); } private Mono<PollResult<BuildInner>> enqueueBuild(ResourceUploadDefinition option, PollingContext<PollResult<BuildInner>> context) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> { context.setData("buildId", inner.properties().triggeredBuildResult().id()); return new PollResult<>(inner); }); } } }
class SpringAppDeploymentImpl extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp> implements SpringAppDeployment, SpringAppDeployment.Definition<SpringAppImpl, SpringAppDeploymentImpl>, SpringAppDeployment.Update { private static final Duration MAX_BUILD_TIMEOUT = Duration.ofHours(1); private BuildServiceTask buildServiceTask; SpringAppDeploymentImpl(String name, SpringAppImpl parent, DeploymentResourceInner innerObject) { super(name, parent, innerObject); } @Override public String appName() { if (innerModel().properties() == null) { return null; } return innerModel().name(); } @Override public DeploymentSettings settings() { if (innerModel().properties() == null) { return null; } return innerModel().properties().deploymentSettings(); } @Override public DeploymentResourceStatus status() { if (innerModel().properties() == null) { return null; } return innerModel().properties().status(); } @Override public boolean isActive() { if (innerModel().properties() == null) { return false; } return innerModel().properties().active(); } @Override public List<DeploymentInstance> instances() { if (innerModel().properties() == null) { return null; } return innerModel().properties().instances(); } @Override public void start() { startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().serviceClient().getDeployments().startAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void stop() { stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().serviceClient().getDeployments().stopAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void restart() { restartAsync().block(); } @Override public Mono<Void> restartAsync() { return manager().serviceClient().getDeployments().restartAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String getLogFileUrl() { return getLogFileUrlAsync().block(); } @Override public Mono<String> getLogFileUrlAsync() { return manager().serviceClient().getDeployments().getLogFileUrlAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ) .map(LogFileUrlResponseInner::url); } @Override private void ensureDeploySettings() { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().deploymentSettings() == null) { innerModel().properties().withDeploymentSettings(new DeploymentSettings()); } if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } } private void ensureSource() { ensureSource(null); } private void ensureSource(UserSourceType type) { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().source() == null) { if (type == UserSourceType.JAR) { innerModel().properties().withSource(new JarUploadedUserSourceInfo()); } else if (type == UserSourceType.SOURCE) { innerModel().properties().withSource(new SourceUploadedUserSourceInfo()); } else if (type == UserSourceType.NET_CORE_ZIP) { innerModel().properties().withSource(new NetCoreZipUploadedUserSourceInfo()); } else if (type == UserSourceType.BUILD_RESULT) { innerModel().properties().withSource(new BuildResultUserSourceInfo()); } else { innerModel().properties().withSource(new UserSourceInfo()); } } } @Override public SpringAppDeploymentImpl withJarFile(File jar) { if (service().isEnterpriseTier()) { return withJarFile(jar, null); } else { ensureSource(UserSourceType.JAR); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorageAsync(jar, option) .then(context.voidMono()); }) ); return this; } } private ShareFileAsyncClient createShareFileAsyncClient(ResourceUploadDefinition option) { return new ShareFileClientBuilder() .endpoint(option.uploadUrl()) .httpClient(manager().httpPipeline().getHttpClient()) .buildFileAsyncClient(); } private Mono<Void> uploadToStorageAsync(File source, ResourceUploadDefinition option) { try { ShareFileAsyncClient shareFileAsyncClient = createShareFileAsyncClient(option); return shareFileAsyncClient.create(source.length()) .flatMap(fileInfo -> shareFileAsyncClient.uploadFromFile(source.getAbsolutePath())) .then(Mono.empty()); } catch (Exception e) { return Mono.error(e); } } @Override public SpringAppDeploymentImpl withExistingSource(UserSourceType type, String relativePath) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); UserSourceInfo sourceInfo = innerModel().properties().source(); if (sourceInfo instanceof BuildResultUserSourceInfo) { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) sourceInfo; userSourceInfo.withBuildResultId(relativePath); } } else { ensureSource(type); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRelativePath(relativePath); } } return this; } @Override public SpringAppDeploymentImpl withJarFile(File jar, List<String> configFilePatterns) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(jar, configFilePatterns); return this; } private boolean isEnterpriseTier() { return service().isEnterpriseTier(); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz) { return withSourceCodeTarGzFile(sourceCodeTarGz, null); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz, List<String> configFilePatterns) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(sourceCodeTarGz, configFilePatterns, true); } else { ensureSource(UserSourceType.SOURCE); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorageAsync(sourceCodeTarGz, option) .then(context.voidMono()); }) ); } return this; } @Override public SpringAppDeploymentImpl withTargetModule(String moduleName) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask.module = moduleName; } else { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(moduleName); } } return this; } @Override public SpringAppDeploymentImpl withSingleModule() { return withTargetModule(null); } @Override public SpringAppDeploymentImpl withInstance(int count) { if (innerModel().sku() == null) { innerModel().withSku(service().sku()); } if (innerModel().sku() == null) { innerModel().withSku(new Sku().withName("B0")); } innerModel().sku().withCapacity(count); return this; } @Override public SpringAppDeploymentImpl withCpu(int cpuCount) { return withCpu(String.valueOf(cpuCount)); } @Override public SpringAppDeploymentImpl withCpu(String cpuCount) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withCpu(cpuCount); return this; } @Override public SpringAppDeploymentImpl withMemory(int sizeInGB) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(String.format("%dGi", sizeInGB)); return this; } @Override public SpringAppDeploymentImpl withMemory(String size) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(size); return this; } @Override public SpringAppDeploymentImpl withRuntime(RuntimeVersion version) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof NetCoreZipUploadedUserSourceInfo) { NetCoreZipUploadedUserSourceInfo uploadedUserSourceInfo = (NetCoreZipUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo uploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } return this; } @Override public SpringAppDeploymentImpl withJvmOptions(String jvmOptions) { if (isEnterpriseTier()) { withEnvironment("JAVA_OPTS", jvmOptions); } else { ensureSource(UserSourceType.JAR); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withJvmOptions(jvmOptions); } } return this; } private void ensureEnvironments() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().environmentVariables() == null) { innerModel().properties().deploymentSettings().withEnvironmentVariables(new HashMap<>()); } } private void ensureAddonConfigs() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().addonConfigs() == null) { innerModel().properties().deploymentSettings().withAddonConfigs(new HashMap<>()); } } @Override public SpringAppDeploymentImpl withEnvironment(String key, String value) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().put(key, value); return this; } @Override public SpringAppDeploymentImpl withoutEnvironment(String key) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().remove(key); return this; } @Override public SpringAppDeploymentImpl withVersionName(String versionName) { ensureSource(); innerModel().properties().source().withVersion(versionName); return this; } @Override public SpringAppDeploymentImpl withActivation() { this.addPostRunDependent( context -> parent().update().withActiveDeployment(name()).applyAsync() .map(Function.identity()) ); return this; } @Override public SpringAppDeploymentImpl withConfigFilePatterns(List<String> configFilePatterns) { ensureAddonConfigs(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().deploymentSettings().addonConfigs(); addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, s -> { Map<String, Object> config = new HashMap<>(); config.put( Constants.CONFIG_FILE_PATTERNS_KEY, CoreUtils.isNullOrEmpty(configFilePatterns) ? "" : String.join(",", configFilePatterns)); return config; }); return this; } @Override public void beforeGroupCreateOrUpdate() { super.beforeGroupCreateOrUpdate(); if (this.buildServiceTask != null) { this.addDependency(this.buildServiceTask); this.buildServiceTask = null; } } @Override public Mono<SpringAppDeployment> createResourceAsync() { return manager().serviceClient().getDeployments().createOrUpdateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<SpringAppDeployment> updateResourceAsync() { return manager().serviceClient().getDeployments().updateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getDeployments().deleteAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override protected Mono<DeploymentResourceInner> getInnerAsync() { return manager().serviceClient().getDeployments().getAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String id() { return innerModel().id(); } @Override public SpringAppDeploymentImpl update() { prepareUpdate(); return this; } private AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl attach() { return parent().addActiveDeployment(this); } private SpringAppImpl app() { return parent(); } private SpringServiceImpl service() { return parent().parent(); } private class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { AtomicLong pollCount = new AtomicLong(); Duration pollDuration = manager().serviceClient().getDefaultPollInterval(); return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultWithResponseAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(response -> { if (pollDuration.multipliedBy(pollCount.get()).compareTo(MAX_BUILD_TIMEOUT) < 0) { BuildResultProvisioningState state = response.getValue().properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return Mono.error(new ManagementException(String.format("Build failed for file: %s, buildId: %s", file.getName(), buildId), new HttpResponseImpl<>(response, client.getSerializerAdapter()))); } } else { return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", file.getName(), buildId), null)); } }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> { pollCount.set(index); return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); }))); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } @SuppressWarnings("BlockingMethodInNonBlockingContext") private class HttpResponseImpl<T> extends HttpResponse { private final Response<T> response; private final SerializerAdapter serializerAdapter; protected HttpResponseImpl(Response<T> response, SerializerAdapter serializerAdapter) { super(response.getRequest()); this.response = response; this.serializerAdapter = serializerAdapter; } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public String getHeaderValue(String header) { return response.getHeaders().getValue(header); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { try { return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } } @Override public Mono<byte[]> getBodyAsByteArray() { try { return Mono.just(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON)); } catch (IOException e) { return Mono.empty(); } } @Override public Mono<String> getBodyAsString() { return Mono.just(serializerAdapter.serializeRaw(response.getValue())); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsString(); } } } }
Why it is called `configFilePatterns`?
public void canCRUDEnterpriseTierDeployment() throws Exception { allowAllSSL(); File tarGzFile = downloadFile(PETCLINIC_TAR_GZ_URL); File jarFile = downloadFile(PETCLINIC_GATEWAY_JAR_URL); String serviceName = generateRandomResourceName("springsvc", 15); Region region = Region.US_EAST; List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service"); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .withEnterpriseTierSku() .withDefaultGitRepository(PETCLINIC_CONFIG_URL, "master", configFilePatterns) .create(); String deploymentName = generateRandomResourceName("deploy", 15); List<String> apiGatewayConfigFilePatterns = Arrays.asList("api-gateway"); String appName = "api-gateway"; SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu("500m") .withMemory("512Mi") .attach() .withDefaultPublicEndpoint() .withConfigurationServiceBinding() .create(); SpringAppDeployment deployment = app.deployments().getByName(deploymentName); Assertions.assertTrue(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); deployment.update() .withConfigFilePatterns(apiGatewayConfigFilePatterns) .apply(); deployment.refresh(); Assertions.assertFalse(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); String appName2 = "customers-service"; String module = "spring-petclinic-customers-service"; List<String> customerServiceConfigFilePatterns = Arrays.asList("customers-service"); SpringApp app2 = service.apps().define(appName2) .defineActiveDeployment(deploymentName) .withSourceCodeTarGzFile(tarGzFile, customerServiceConfigFilePatterns) .withTargetModule(module) .attach() .withConfigurationServiceBinding() .create(); Assertions.assertNull(app2.url()); SpringAppDeployment customersDeployment = app2.deployments().getByName(deploymentName); Assertions.assertEquals(customerServiceConfigFilePatterns, customersDeployment.configFilePatterns()); }
List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service");
public void canCRUDEnterpriseTierDeployment() throws Exception { allowAllSSL(); File tarGzFile = downloadFile(PETCLINIC_TAR_GZ_URL); File jarFile = downloadFile(PETCLINIC_GATEWAY_JAR_URL); String serviceName = generateRandomResourceName("springsvc", 15); Region region = Region.US_EAST; List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service"); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .withEnterpriseTierSku() .withDefaultGitRepository(PETCLINIC_CONFIG_URL, "master", configFilePatterns) .create(); String deploymentName = generateRandomResourceName("deploy", 15); List<String> apiGatewayConfigFilePatterns = Arrays.asList("api-gateway"); String appName = "api-gateway"; SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu("500m") .withMemory("512Mi") .attach() .withDefaultPublicEndpoint() .withConfigurationServiceBinding() .create(); SpringAppDeployment deployment = app.deployments().getByName(deploymentName); Assertions.assertTrue(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); deployment.update() .withConfigFilePatterns(apiGatewayConfigFilePatterns) .apply(); deployment.refresh(); Assertions.assertFalse(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); String appName2 = "customers-service"; String module = "spring-petclinic-customers-service"; List<String> customerServiceConfigFilePatterns = Arrays.asList("customers-service"); SpringApp app2 = service.apps().define(appName2) .defineActiveDeployment(deploymentName) .withSourceCodeTarGzFile(tarGzFile, customerServiceConfigFilePatterns) .withTargetModule(module) .attach() .withConfigurationServiceBinding() .create(); Assertions.assertNull(app2.url()); SpringAppDeployment customersDeployment = app2.deployments().getByName(deploymentName); Assertions.assertEquals(customerServiceConfigFilePatterns, customersDeployment.configFilePatterns()); }
class SpringCloudLiveOnlyTest extends AppPlatformTest { private static final String PIGGYMETRICS_CONFIG_URL = "https: private static final String GATEWAY_JAR_URL = "https: private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String PETCLINIC_CONFIG_URL = "https: private static final String PETCLINIC_GATEWAY_JAR_URL = "https: private static final String PETCLINIC_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_OBJECT_ID = "938df8e2-2b9d-40b1-940c-c75c33494239"; @Test @DoNotRecord(skipInPlayback = true) public void canCRUDDeployment() throws Exception { allowAllSSL(); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; String deploymentName = generateRandomResourceName("deploy", 15); String deploymentName1 = generateRandomResourceName("deploy", 15); Region region = Region.US_EAST; SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .create(); File jarFile = downloadFile(GATEWAY_JAR_URL); SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu(2) .withMemory(4) .withRuntime(RuntimeVersion.JAVA_11) .attach() .withDefaultPublicEndpoint() .create(); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); Assertions.assertTrue(requestSuccess(app.url())); SpringAppDeployment deployment = app.getActiveDeployment(); Assertions.assertEquals("2", deployment.settings().resourceRequests().cpu()); Assertions.assertEquals("4Gi", deployment.settings().resourceRequests().memory()); Assertions.assertEquals(2, deployment.instances().size()); File gzFile = downloadFile(PIGGYMETRICS_TAR_GZ_URL); deployment = app.deployments().define(deploymentName1) .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .withActivation() .create(); app.refresh(); Assertions.assertEquals(deploymentName1, app.activeDeploymentName()); Assertions.assertEquals("1", deployment.settings().resourceRequests().cpu()); Assertions.assertNotNull(deployment.getLogFileUrl()); Assertions.assertTrue(requestSuccess(app.url())); app.update() .withoutDefaultPublicEndpoint() .apply(); Assertions.assertFalse(app.isPublic()); app.deployments().deleteByName(deploymentName); Assertions.assertEquals(1, app.deployments().list().stream().count()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateCustomDomainWithSsl() throws Exception { String domainName = generateRandomResourceName("jsdkdemo-", 20) + ".com"; String certOrderName = generateRandomResourceName("cert", 15); String vaultName = generateRandomResourceName("vault", 15); String certName = generateRandomResourceName("cert", 15); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; Region region = Region.US_EAST; allowAllSSL(); String cerPassword = password(); String resourcePath = Paths.get(this.getClass().getResource("/session-records").toURI()).getParent().toString(); String cerPath = resourcePath + domainName + ".cer"; String pfxPath = resourcePath + domainName + ".pfx"; createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); appPlatformManager.resourceManager().resourceGroups().define(rgName) .withRegion(region) .create(); DnsZone dnsZone = dnsZoneManager.zones().define(domainName) .withExistingResourceGroup(rgName) .create(); AppServiceDomain domain = appServiceManager.domains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .withExistingDnsZone(dnsZone) .create(); Vault vault = keyVaultManager.vaults().define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(SPRING_CLOUD_SERVICE_OBJECT_ID) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(appPlatformManager.httpPipeline()) .buildClient(); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setPassword(cerPassword) .setEnabled(true) ); KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); String alias = Collections.list(store.aliases()).get(0); String thumbprint = printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .withCertificate("test", vault.vaultUri(), certName) .create(); service.apps().define(appName).withDefaultActiveDeployment().withDefaultPublicEndpoint().create(); SpringApp app = service.apps().getByName(appName); dnsZone.update() .withCNameRecordSet("www", app.fqdn()) .withCNameRecordSet("ssl", app.fqdn()) .apply(); app.update() .withoutDefaultPublicEndpoint() .withCustomDomain(String.format("www.%s", domainName)) .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); Assertions.assertTrue(app.customDomains().validate(String.format("www.%s", domainName)).isValid()); Assertions.assertTrue(requestSuccess(String.format("http: Assertions.assertTrue(requestSuccess(String.format("https: app.update() .withHttpsOnly() .withoutCustomDomain(String.format("www.%s", domainName)) .apply(); Assertions.assertTrue(checkRedirect(String.format("http: } @Test @DoNotRecord(skipInPlayback = true) private File downloadFile(String remoteFileUrl) throws Exception { String[] split = remoteFileUrl.split("/"); String filename = split[split.length - 1]; File downloaded = new File(filename); if (!downloaded.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(remoteFileUrl).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(downloaded)) { IOUtils.copy(inputStream, outputStream); } finally { connection.disconnect(); } } return downloaded; } private void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } private byte[] readAllBytes(InputStream inputStream) throws IOException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { byte[] data = new byte[4096]; while (true) { int size = inputStream.read(data); if (size > 0) { outputStream.write(data, 0, size); } else { return outputStream.toByteArray(); } } } } public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName, String dnsName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; if (dnsName != null) { List<String> args = new ArrayList<>(Arrays.asList(commandArgs)); args.add("-ext"); args.add("san=dns:" + dnsName); commandArgs = args.toArray(new String[0]); } cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!"".equals(error))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } private static final char[] HEX_CODE = "0123456789ABCDEF".toCharArray(); private static String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder(data.length * 2); for (byte b : data) { r.append(HEX_CODE[(b >> 4) & 0xF]); r.append(HEX_CODE[(b & 0xF)]); } return r.toString(); } }
class SpringCloudLiveOnlyTest extends AppPlatformTest { private static final String PIGGYMETRICS_CONFIG_URL = "https: private static final String GATEWAY_JAR_URL = "https: private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String PETCLINIC_CONFIG_URL = "https: private static final String PETCLINIC_GATEWAY_JAR_URL = "https: private static final String PETCLINIC_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_OBJECT_ID = "938df8e2-2b9d-40b1-940c-c75c33494239"; @Test @DoNotRecord(skipInPlayback = true) public void canCRUDDeployment() throws Exception { allowAllSSL(); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; String deploymentName = generateRandomResourceName("deploy", 15); String deploymentName1 = generateRandomResourceName("deploy", 15); Region region = Region.US_EAST; SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .create(); File jarFile = downloadFile(GATEWAY_JAR_URL); SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu(2) .withMemory(4) .withRuntime(RuntimeVersion.JAVA_11) .attach() .withDefaultPublicEndpoint() .create(); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); Assertions.assertTrue(requestSuccess(app.url())); SpringAppDeployment deployment = app.getActiveDeployment(); Assertions.assertEquals("2", deployment.settings().resourceRequests().cpu()); Assertions.assertEquals("4Gi", deployment.settings().resourceRequests().memory()); Assertions.assertEquals(2, deployment.instances().size()); File gzFile = downloadFile(PIGGYMETRICS_TAR_GZ_URL); deployment = app.deployments().define(deploymentName1) .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .withActivation() .create(); app.refresh(); Assertions.assertEquals(deploymentName1, app.activeDeploymentName()); Assertions.assertEquals("1", deployment.settings().resourceRequests().cpu()); Assertions.assertNotNull(deployment.getLogFileUrl()); Assertions.assertTrue(requestSuccess(app.url())); app.update() .withoutDefaultPublicEndpoint() .apply(); Assertions.assertFalse(app.isPublic()); app.deployments().deleteByName(deploymentName); Assertions.assertEquals(1, app.deployments().list().stream().count()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateCustomDomainWithSsl() throws Exception { String domainName = generateRandomResourceName("jsdkdemo-", 20) + ".com"; String certOrderName = generateRandomResourceName("cert", 15); String vaultName = generateRandomResourceName("vault", 15); String certName = generateRandomResourceName("cert", 15); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; Region region = Region.US_EAST; allowAllSSL(); String cerPassword = password(); String resourcePath = Paths.get(this.getClass().getResource("/session-records").toURI()).getParent().toString(); String cerPath = resourcePath + domainName + ".cer"; String pfxPath = resourcePath + domainName + ".pfx"; createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); appPlatformManager.resourceManager().resourceGroups().define(rgName) .withRegion(region) .create(); DnsZone dnsZone = dnsZoneManager.zones().define(domainName) .withExistingResourceGroup(rgName) .create(); AppServiceDomain domain = appServiceManager.domains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .withExistingDnsZone(dnsZone) .create(); Vault vault = keyVaultManager.vaults().define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(SPRING_CLOUD_SERVICE_OBJECT_ID) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(appPlatformManager.httpPipeline()) .buildClient(); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setPassword(cerPassword) .setEnabled(true) ); KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); String alias = Collections.list(store.aliases()).get(0); String thumbprint = printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .withCertificate("test", vault.vaultUri(), certName) .create(); service.apps().define(appName).withDefaultActiveDeployment().withDefaultPublicEndpoint().create(); SpringApp app = service.apps().getByName(appName); dnsZone.update() .withCNameRecordSet("www", app.fqdn()) .withCNameRecordSet("ssl", app.fqdn()) .apply(); app.update() .withoutDefaultPublicEndpoint() .withCustomDomain(String.format("www.%s", domainName)) .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); Assertions.assertTrue(app.customDomains().validate(String.format("www.%s", domainName)).isValid()); Assertions.assertTrue(requestSuccess(String.format("http: Assertions.assertTrue(requestSuccess(String.format("https: app.update() .withHttpsOnly() .withoutCustomDomain(String.format("www.%s", domainName)) .apply(); Assertions.assertTrue(checkRedirect(String.format("http: } @Test @DoNotRecord(skipInPlayback = true) private File downloadFile(String remoteFileUrl) throws Exception { String[] split = remoteFileUrl.split("/"); String filename = split[split.length - 1]; File downloaded = new File(filename); if (!downloaded.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(remoteFileUrl).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(downloaded)) { IOUtils.copy(inputStream, outputStream); } finally { connection.disconnect(); } } return downloaded; } private void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } private byte[] readAllBytes(InputStream inputStream) throws IOException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { byte[] data = new byte[4096]; while (true) { int size = inputStream.read(data); if (size > 0) { outputStream.write(data, 0, size); } else { return outputStream.toByteArray(); } } } } public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName, String dnsName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; if (dnsName != null) { List<String> args = new ArrayList<>(Arrays.asList(commandArgs)); args.add("-ext"); args.add("san=dns:" + dnsName); commandArgs = args.toArray(new String[0]); } cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!"".equals(error))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } private static final char[] HEX_CODE = "0123456789ABCDEF".toCharArray(); private static String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder(data.length * 2); for (byte b : data) { r.append(HEX_CODE[(b >> 4) & 0xF]); r.append(HEX_CODE[(b & 0xF)]); } return r.toString(); } }
sure
public List<String> configFilePatterns() { Map<String, Map<String, Object>> addonConfigs = this.innerModel().properties().deploymentSettings().addonConfigs(); if (addonConfigs == null) { return Collections.emptyList(); } Map<String, Object> configurationConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationConfigs == null) { return Collections.emptyList(); } String patterns = (String) configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY); if (CoreUtils.isNullOrEmpty(patterns)) { return Collections.emptyList(); } return Arrays.asList(patterns.split(",")); }
return Arrays.asList(patterns.split(","));
public List<String> configFilePatterns() { Map<String, Map<String, Object>> addonConfigs = this.innerModel().properties().deploymentSettings().addonConfigs(); if (addonConfigs == null) { return Collections.emptyList(); } Map<String, Object> configurationConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationConfigs == null) { return Collections.emptyList(); } if (configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY) instanceof String) { String patterns = (String) configurationConfigs.get(Constants.CONFIG_FILE_PATTERNS_KEY); return Collections.unmodifiableList(Arrays.asList(patterns.split(","))); } else { return Collections.emptyList(); } }
class SpringAppDeploymentImpl extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp> implements SpringAppDeployment, SpringAppDeployment.Definition<SpringAppImpl, SpringAppDeploymentImpl>, SpringAppDeployment.Update { private BuildServiceTask buildServiceTask; SpringAppDeploymentImpl(String name, SpringAppImpl parent, DeploymentResourceInner innerObject) { super(name, parent, innerObject); } @Override public String appName() { if (innerModel().properties() == null) { return null; } return innerModel().name(); } @Override public DeploymentSettings settings() { if (innerModel().properties() == null) { return null; } return innerModel().properties().deploymentSettings(); } @Override public DeploymentResourceStatus status() { if (innerModel().properties() == null) { return null; } return innerModel().properties().status(); } @Override public boolean isActive() { if (innerModel().properties() == null) { return false; } return innerModel().properties().active(); } @Override public List<DeploymentInstance> instances() { if (innerModel().properties() == null) { return null; } return innerModel().properties().instances(); } @Override public void start() { startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().serviceClient().getDeployments().startAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void stop() { stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().serviceClient().getDeployments().stopAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void restart() { restartAsync().block(); } @Override public Mono<Void> restartAsync() { return manager().serviceClient().getDeployments().restartAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String getLogFileUrl() { return getLogFileUrlAsync().block(); } @Override public Mono<String> getLogFileUrlAsync() { return manager().serviceClient().getDeployments().getLogFileUrlAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ) .map(LogFileUrlResponseInner::url); } @Override private void ensureDeploySettings() { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().deploymentSettings() == null) { innerModel().properties().withDeploymentSettings(new DeploymentSettings()); } if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } } private void ensureSource() { ensureSource(null); } private void ensureSource(UserSourceType type) { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().source() == null) { if (type == UserSourceType.JAR) { innerModel().properties().withSource(new JarUploadedUserSourceInfo()); } else if (type == UserSourceType.SOURCE) { innerModel().properties().withSource(new SourceUploadedUserSourceInfo()); } else if (type == UserSourceType.NET_CORE_ZIP) { innerModel().properties().withSource(new NetCoreZipUploadedUserSourceInfo()); } else if (type == UserSourceType.BUILD_RESULT) { innerModel().properties().withSource(new BuildResultUserSourceInfo()); } else { innerModel().properties().withSource(new UserSourceInfo()); } } } @Override public SpringAppDeploymentImpl withJarFile(File jar) { if (service().isEnterpriseTier()) { return withJarFile(jar, null); } else { ensureSource(UserSourceType.JAR); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorage(jar, option) .then(context.voidMono()); }) ); return this; } } private ShareFileAsyncClient createShareFileAsyncClient(ResourceUploadDefinition option) { return new ShareFileClientBuilder() .endpoint(option.uploadUrl()) .httpClient(manager().httpPipeline().getHttpClient()) .buildFileAsyncClient(); } private Mono<Void> uploadToStorage(File source, ResourceUploadDefinition option) { try { ShareFileAsyncClient shareFileAsyncClient = createShareFileAsyncClient(option); return shareFileAsyncClient.create(source.length()) .flatMap(fileInfo -> shareFileAsyncClient.uploadFromFile(source.getAbsolutePath())) .then(Mono.empty()); } catch (Exception e) { return Mono.error(e); } } @Override public SpringAppDeploymentImpl withExistingSource(UserSourceType type, String relativePath) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); UserSourceInfo sourceInfo = innerModel().properties().source(); if (sourceInfo instanceof BuildResultUserSourceInfo) { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) sourceInfo; userSourceInfo.withBuildResultId(relativePath); } } else { ensureSource(type); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRelativePath(relativePath); } } return this; } @Override public SpringAppDeploymentImpl withJarFile(File jar, List<String> configFilePatterns) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(jar, configFilePatterns); return this; } private boolean isEnterpriseTier() { return service().isEnterpriseTier(); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz) { return withSourceCodeTarGzFile(sourceCodeTarGz, null); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz, List<String> configFilePatterns) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(sourceCodeTarGz, configFilePatterns, true); } else { ensureSource(UserSourceType.SOURCE); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorage(sourceCodeTarGz, option) .then(context.voidMono()); }) ); } return this; } @Override public SpringAppDeploymentImpl withTargetModule(String moduleName) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask.module = moduleName; } else { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(moduleName); } } return this; } @Override public SpringAppDeploymentImpl withSingleModule() { return withTargetModule(null); } @Override public SpringAppDeploymentImpl withInstance(int count) { if (innerModel().sku() == null) { innerModel().withSku(service().sku()); } if (innerModel().sku() == null) { innerModel().withSku(new Sku().withName("B0")); } innerModel().sku().withCapacity(count); return this; } @Override public SpringAppDeploymentImpl withCpu(int cpuCount) { return withCpu(String.valueOf(cpuCount)); } @Override public SpringAppDeploymentImpl withCpu(String cpuCount) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withCpu(cpuCount); return this; } @Override public SpringAppDeploymentImpl withMemory(int sizeInGB) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(String.format("%dGi", sizeInGB)); return this; } @Override public SpringAppDeploymentImpl withMemory(String size) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(size); return this; } @Override public SpringAppDeploymentImpl withRuntime(RuntimeVersion version) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof NetCoreZipUploadedUserSourceInfo) { NetCoreZipUploadedUserSourceInfo uploadedUserSourceInfo = (NetCoreZipUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo uploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } return this; } @Override public SpringAppDeploymentImpl withJvmOptions(String jvmOptions) { if (isEnterpriseTier()) { withEnvironment("JAVA_OPTS", jvmOptions); } else { ensureSource(UserSourceType.JAR); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withJvmOptions(jvmOptions); } } return this; } private void ensureEnvironments() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().environmentVariables() == null) { innerModel().properties().deploymentSettings().withEnvironmentVariables(new HashMap<>()); } } private void ensureAddonConfigs() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().addonConfigs() == null) { innerModel().properties().deploymentSettings().withAddonConfigs(new HashMap<>()); } } @Override public SpringAppDeploymentImpl withEnvironment(String key, String value) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().put(key, value); return this; } @Override public SpringAppDeploymentImpl withoutEnvironment(String key) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().remove(key); return this; } @Override public SpringAppDeploymentImpl withVersionName(String versionName) { ensureSource(); innerModel().properties().source().withVersion(versionName); return this; } @Override public SpringAppDeploymentImpl withActivation() { this.addPostRunDependent( context -> parent().update().withActiveDeployment(name()).applyAsync() .map(Function.identity()) ); return this; } @Override public SpringAppDeploymentImpl withConfigFilePatterns(List<String> configFilePatterns) { ensureAddonConfigs(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().deploymentSettings().addonConfigs(); addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, s -> { Map<String, Object> config = new HashMap<>(); config.put( Constants.CONFIG_FILE_PATTERNS_KEY, CoreUtils.isNullOrEmpty(configFilePatterns) ? "" : String.join(",", configFilePatterns)); return config; }); return this; } @Override public void beforeGroupCreateOrUpdate() { super.beforeGroupCreateOrUpdate(); if (this.buildServiceTask != null) { this.addDependency(this.buildServiceTask); this.buildServiceTask = null; } } @Override public Mono<SpringAppDeployment> createResourceAsync() { return manager().serviceClient().getDeployments().createOrUpdateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<SpringAppDeployment> updateResourceAsync() { return manager().serviceClient().getDeployments().updateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getDeployments().deleteAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override protected Mono<DeploymentResourceInner> getInnerAsync() { return manager().serviceClient().getDeployments().getAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String id() { return innerModel().id(); } @Override public SpringAppDeploymentImpl update() { prepareUpdate(); return this; } private AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl attach() { return parent().addActiveDeployment(this); } private SpringAppImpl app() { return parent(); } private SpringServiceImpl service() { return parent().parent(); } private class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuild(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> uploadAndBuild(File source, ResourceUploadDefinition option) { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return uploadToStorage(source, option) .then( new PollerFlux<>( manager().serviceClient().getDefaultPollInterval(), context -> enqueueBuild(option, context), this::waitForBuild, (pollResultPollingContext, pollResultPollResponse) -> Mono.error(new RuntimeException("build canceled")), this::getBuildResult) .last() .flatMap(client::getLroFinalResultOrError) .flatMap((Function<Object, Mono<String>>) o -> { BuildResultInner result = (BuildResultInner) o; return Mono.just(result.id()); }) ); } private Mono<BuildResultInner> getBuildResult(PollingContext<PollResult<BuildInner>> context) { return manager().serviceClient().getBuildServices() .getBuildResultAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(context.getData("buildId"))); } private Mono<PollResponse<PollResult<BuildInner>>> waitForBuild(PollingContext<PollResult<BuildInner>> context) { return getBuildResult(context) .flatMap((Function<BuildResultInner, Mono<PollResponse<PollResult<BuildInner>>>>) buildResultInner -> { BuildResultProvisioningState state = buildResultInner.properties().provisioningState(); PollResult<BuildInner> emptyResult = new PollResult<>(new BuildInner().withProperties(new BuildProperties())); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, emptyResult)); } else if (state == BuildResultProvisioningState.FAILED || state == BuildResultProvisioningState.DELETING) { return Mono.error(new RuntimeException("build failed")); } else if (state == BuildResultProvisioningState.QUEUING) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, emptyResult)); } return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, emptyResult)); }); } private Mono<PollResult<BuildInner>> enqueueBuild(ResourceUploadDefinition option, PollingContext<PollResult<BuildInner>> context) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> { context.setData("buildId", inner.properties().triggeredBuildResult().id()); return new PollResult<>(inner); }); } } }
class SpringAppDeploymentImpl extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp> implements SpringAppDeployment, SpringAppDeployment.Definition<SpringAppImpl, SpringAppDeploymentImpl>, SpringAppDeployment.Update { private static final Duration MAX_BUILD_TIMEOUT = Duration.ofHours(1); private BuildServiceTask buildServiceTask; SpringAppDeploymentImpl(String name, SpringAppImpl parent, DeploymentResourceInner innerObject) { super(name, parent, innerObject); } @Override public String appName() { if (innerModel().properties() == null) { return null; } return innerModel().name(); } @Override public DeploymentSettings settings() { if (innerModel().properties() == null) { return null; } return innerModel().properties().deploymentSettings(); } @Override public DeploymentResourceStatus status() { if (innerModel().properties() == null) { return null; } return innerModel().properties().status(); } @Override public boolean isActive() { if (innerModel().properties() == null) { return false; } return innerModel().properties().active(); } @Override public List<DeploymentInstance> instances() { if (innerModel().properties() == null) { return null; } return innerModel().properties().instances(); } @Override public void start() { startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().serviceClient().getDeployments().startAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void stop() { stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().serviceClient().getDeployments().stopAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public void restart() { restartAsync().block(); } @Override public Mono<Void> restartAsync() { return manager().serviceClient().getDeployments().restartAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String getLogFileUrl() { return getLogFileUrlAsync().block(); } @Override public Mono<String> getLogFileUrlAsync() { return manager().serviceClient().getDeployments().getLogFileUrlAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ) .map(LogFileUrlResponseInner::url); } @Override private void ensureDeploySettings() { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().deploymentSettings() == null) { innerModel().properties().withDeploymentSettings(new DeploymentSettings()); } if (innerModel().properties().deploymentSettings().resourceRequests() == null) { innerModel().properties().deploymentSettings().withResourceRequests(new ResourceRequests()); } } private void ensureSource() { ensureSource(null); } private void ensureSource(UserSourceType type) { if (innerModel().properties() == null) { innerModel().withProperties(new DeploymentResourceProperties()); } if (innerModel().properties().source() == null) { if (type == UserSourceType.JAR) { innerModel().properties().withSource(new JarUploadedUserSourceInfo()); } else if (type == UserSourceType.SOURCE) { innerModel().properties().withSource(new SourceUploadedUserSourceInfo()); } else if (type == UserSourceType.NET_CORE_ZIP) { innerModel().properties().withSource(new NetCoreZipUploadedUserSourceInfo()); } else if (type == UserSourceType.BUILD_RESULT) { innerModel().properties().withSource(new BuildResultUserSourceInfo()); } else { innerModel().properties().withSource(new UserSourceInfo()); } } } @Override public SpringAppDeploymentImpl withJarFile(File jar) { if (service().isEnterpriseTier()) { return withJarFile(jar, null); } else { ensureSource(UserSourceType.JAR); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorageAsync(jar, option) .then(context.voidMono()); }) ); return this; } } private ShareFileAsyncClient createShareFileAsyncClient(ResourceUploadDefinition option) { return new ShareFileClientBuilder() .endpoint(option.uploadUrl()) .httpClient(manager().httpPipeline().getHttpClient()) .buildFileAsyncClient(); } private Mono<Void> uploadToStorageAsync(File source, ResourceUploadDefinition option) { try { ShareFileAsyncClient shareFileAsyncClient = createShareFileAsyncClient(option); return shareFileAsyncClient.create(source.length()) .flatMap(fileInfo -> shareFileAsyncClient.uploadFromFile(source.getAbsolutePath())) .then(Mono.empty()); } catch (Exception e) { return Mono.error(e); } } @Override public SpringAppDeploymentImpl withExistingSource(UserSourceType type, String relativePath) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); UserSourceInfo sourceInfo = innerModel().properties().source(); if (sourceInfo instanceof BuildResultUserSourceInfo) { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) sourceInfo; userSourceInfo.withBuildResultId(relativePath); } } else { ensureSource(type); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof UploadedUserSourceInfo) { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRelativePath(relativePath); } } return this; } @Override public SpringAppDeploymentImpl withJarFile(File jar, List<String> configFilePatterns) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(jar, configFilePatterns); return this; } private boolean isEnterpriseTier() { return service().isEnterpriseTier(); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz) { return withSourceCodeTarGzFile(sourceCodeTarGz, null); } @Override public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz, List<String> configFilePatterns) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask = new BuildServiceTask(sourceCodeTarGz, configFilePatterns, true); } else { ensureSource(UserSourceType.SOURCE); this.addDependency( context -> parent().getResourceUploadUrlAsync() .flatMap(option -> { UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); uploadedUserSourceInfo.withRelativePath(option.relativePath()); return uploadToStorageAsync(sourceCodeTarGz, option) .then(context.voidMono()); }) ); } return this; } @Override public SpringAppDeploymentImpl withTargetModule(String moduleName) { if (isEnterpriseTier()) { ensureSource(UserSourceType.BUILD_RESULT); this.buildServiceTask.module = moduleName; } else { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(moduleName); } } return this; } @Override public SpringAppDeploymentImpl withSingleModule() { return withTargetModule(null); } @Override public SpringAppDeploymentImpl withInstance(int count) { if (innerModel().sku() == null) { innerModel().withSku(service().sku()); } if (innerModel().sku() == null) { innerModel().withSku(new Sku().withName("B0")); } innerModel().sku().withCapacity(count); return this; } @Override public SpringAppDeploymentImpl withCpu(int cpuCount) { return withCpu(String.valueOf(cpuCount)); } @Override public SpringAppDeploymentImpl withCpu(String cpuCount) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withCpu(cpuCount); return this; } @Override public SpringAppDeploymentImpl withMemory(int sizeInGB) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(String.format("%dGi", sizeInGB)); return this; } @Override public SpringAppDeploymentImpl withMemory(String size) { ensureDeploySettings(); innerModel().properties().deploymentSettings().resourceRequests().withMemory(size); return this; } @Override public SpringAppDeploymentImpl withRuntime(RuntimeVersion version) { UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof NetCoreZipUploadedUserSourceInfo) { NetCoreZipUploadedUserSourceInfo uploadedUserSourceInfo = (NetCoreZipUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } else if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { SourceUploadedUserSourceInfo uploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withRuntimeVersion(version.toString()); } return this; } @Override public SpringAppDeploymentImpl withJvmOptions(String jvmOptions) { if (isEnterpriseTier()) { withEnvironment("JAVA_OPTS", jvmOptions); } else { ensureSource(UserSourceType.JAR); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof JarUploadedUserSourceInfo) { JarUploadedUserSourceInfo uploadedUserSourceInfo = (JarUploadedUserSourceInfo) userSourceInfo; uploadedUserSourceInfo.withJvmOptions(jvmOptions); } } return this; } private void ensureEnvironments() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().environmentVariables() == null) { innerModel().properties().deploymentSettings().withEnvironmentVariables(new HashMap<>()); } } private void ensureAddonConfigs() { ensureDeploySettings(); if (innerModel().properties().deploymentSettings().addonConfigs() == null) { innerModel().properties().deploymentSettings().withAddonConfigs(new HashMap<>()); } } @Override public SpringAppDeploymentImpl withEnvironment(String key, String value) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().put(key, value); return this; } @Override public SpringAppDeploymentImpl withoutEnvironment(String key) { ensureEnvironments(); innerModel().properties().deploymentSettings().environmentVariables().remove(key); return this; } @Override public SpringAppDeploymentImpl withVersionName(String versionName) { ensureSource(); innerModel().properties().source().withVersion(versionName); return this; } @Override public SpringAppDeploymentImpl withActivation() { this.addPostRunDependent( context -> parent().update().withActiveDeployment(name()).applyAsync() .map(Function.identity()) ); return this; } @Override public SpringAppDeploymentImpl withConfigFilePatterns(List<String> configFilePatterns) { ensureAddonConfigs(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().deploymentSettings().addonConfigs(); addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, s -> { Map<String, Object> config = new HashMap<>(); config.put( Constants.CONFIG_FILE_PATTERNS_KEY, CoreUtils.isNullOrEmpty(configFilePatterns) ? "" : String.join(",", configFilePatterns)); return config; }); return this; } @Override public void beforeGroupCreateOrUpdate() { super.beforeGroupCreateOrUpdate(); if (this.buildServiceTask != null) { this.addDependency(this.buildServiceTask); this.buildServiceTask = null; } } @Override public Mono<SpringAppDeployment> createResourceAsync() { return manager().serviceClient().getDeployments().createOrUpdateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<SpringAppDeployment> updateResourceAsync() { return manager().serviceClient().getDeployments().updateAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() ) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getDeployments().deleteAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override protected Mono<DeploymentResourceInner> getInnerAsync() { return manager().serviceClient().getDeployments().getAsync( parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() ); } @Override public String id() { return innerModel().id(); } @Override public SpringAppDeploymentImpl update() { prepareUpdate(); return this; } private AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl attach() { return parent().addActiveDeployment(this); } private SpringAppImpl app() { return parent(); } private SpringServiceImpl service() { return parent().parent(); } private class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { AtomicLong pollCount = new AtomicLong(); Duration pollDuration = manager().serviceClient().getDefaultPollInterval(); return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultWithResponseAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(response -> { if (pollDuration.multipliedBy(pollCount.get()).compareTo(MAX_BUILD_TIMEOUT) < 0) { BuildResultProvisioningState state = response.getValue().properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return Mono.error(new ManagementException(String.format("Build failed for file: %s, buildId: %s", file.getName(), buildId), new HttpResponseImpl<>(response, client.getSerializerAdapter()))); } } else { return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", file.getName(), buildId), null)); } }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> { pollCount.set(index); return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); }))); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } @SuppressWarnings("BlockingMethodInNonBlockingContext") private class HttpResponseImpl<T> extends HttpResponse { private final Response<T> response; private final SerializerAdapter serializerAdapter; protected HttpResponseImpl(Response<T> response, SerializerAdapter serializerAdapter) { super(response.getRequest()); this.response = response; this.serializerAdapter = serializerAdapter; } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public String getHeaderValue(String header) { return response.getHeaders().getValue(header); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { try { return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } } @Override public Mono<byte[]> getBodyAsByteArray() { try { return Mono.just(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON)); } catch (IOException e) { return Mono.empty(); } } @Override public Mono<String> getBodyAsString() { return Mono.just(serializerAdapter.serializeRaw(response.getValue())); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsString(); } } } }
It's a pattern to search for config files in git repositories. Official doc: https://docs.microsoft.com/en-us/azure/spring-cloud/how-to-enterprise-application-configuration-service#pattern User can define several git repositories in Configuration Service. Each git repository has a `configFilePatterns` to search for config files in them. Apps choose the `configFilePatterns` defined in Configuration Service to filter the config files they need.
public void canCRUDEnterpriseTierDeployment() throws Exception { allowAllSSL(); File tarGzFile = downloadFile(PETCLINIC_TAR_GZ_URL); File jarFile = downloadFile(PETCLINIC_GATEWAY_JAR_URL); String serviceName = generateRandomResourceName("springsvc", 15); Region region = Region.US_EAST; List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service"); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .withEnterpriseTierSku() .withDefaultGitRepository(PETCLINIC_CONFIG_URL, "master", configFilePatterns) .create(); String deploymentName = generateRandomResourceName("deploy", 15); List<String> apiGatewayConfigFilePatterns = Arrays.asList("api-gateway"); String appName = "api-gateway"; SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu("500m") .withMemory("512Mi") .attach() .withDefaultPublicEndpoint() .withConfigurationServiceBinding() .create(); SpringAppDeployment deployment = app.deployments().getByName(deploymentName); Assertions.assertTrue(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); deployment.update() .withConfigFilePatterns(apiGatewayConfigFilePatterns) .apply(); deployment.refresh(); Assertions.assertFalse(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); String appName2 = "customers-service"; String module = "spring-petclinic-customers-service"; List<String> customerServiceConfigFilePatterns = Arrays.asList("customers-service"); SpringApp app2 = service.apps().define(appName2) .defineActiveDeployment(deploymentName) .withSourceCodeTarGzFile(tarGzFile, customerServiceConfigFilePatterns) .withTargetModule(module) .attach() .withConfigurationServiceBinding() .create(); Assertions.assertNull(app2.url()); SpringAppDeployment customersDeployment = app2.deployments().getByName(deploymentName); Assertions.assertEquals(customerServiceConfigFilePatterns, customersDeployment.configFilePatterns()); }
List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service");
public void canCRUDEnterpriseTierDeployment() throws Exception { allowAllSSL(); File tarGzFile = downloadFile(PETCLINIC_TAR_GZ_URL); File jarFile = downloadFile(PETCLINIC_GATEWAY_JAR_URL); String serviceName = generateRandomResourceName("springsvc", 15); Region region = Region.US_EAST; List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service"); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .withEnterpriseTierSku() .withDefaultGitRepository(PETCLINIC_CONFIG_URL, "master", configFilePatterns) .create(); String deploymentName = generateRandomResourceName("deploy", 15); List<String> apiGatewayConfigFilePatterns = Arrays.asList("api-gateway"); String appName = "api-gateway"; SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu("500m") .withMemory("512Mi") .attach() .withDefaultPublicEndpoint() .withConfigurationServiceBinding() .create(); SpringAppDeployment deployment = app.deployments().getByName(deploymentName); Assertions.assertTrue(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); deployment.update() .withConfigFilePatterns(apiGatewayConfigFilePatterns) .apply(); deployment.refresh(); Assertions.assertFalse(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); String appName2 = "customers-service"; String module = "spring-petclinic-customers-service"; List<String> customerServiceConfigFilePatterns = Arrays.asList("customers-service"); SpringApp app2 = service.apps().define(appName2) .defineActiveDeployment(deploymentName) .withSourceCodeTarGzFile(tarGzFile, customerServiceConfigFilePatterns) .withTargetModule(module) .attach() .withConfigurationServiceBinding() .create(); Assertions.assertNull(app2.url()); SpringAppDeployment customersDeployment = app2.deployments().getByName(deploymentName); Assertions.assertEquals(customerServiceConfigFilePatterns, customersDeployment.configFilePatterns()); }
class SpringCloudLiveOnlyTest extends AppPlatformTest { private static final String PIGGYMETRICS_CONFIG_URL = "https: private static final String GATEWAY_JAR_URL = "https: private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String PETCLINIC_CONFIG_URL = "https: private static final String PETCLINIC_GATEWAY_JAR_URL = "https: private static final String PETCLINIC_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_OBJECT_ID = "938df8e2-2b9d-40b1-940c-c75c33494239"; @Test @DoNotRecord(skipInPlayback = true) public void canCRUDDeployment() throws Exception { allowAllSSL(); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; String deploymentName = generateRandomResourceName("deploy", 15); String deploymentName1 = generateRandomResourceName("deploy", 15); Region region = Region.US_EAST; SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .create(); File jarFile = downloadFile(GATEWAY_JAR_URL); SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu(2) .withMemory(4) .withRuntime(RuntimeVersion.JAVA_11) .attach() .withDefaultPublicEndpoint() .create(); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); Assertions.assertTrue(requestSuccess(app.url())); SpringAppDeployment deployment = app.getActiveDeployment(); Assertions.assertEquals("2", deployment.settings().resourceRequests().cpu()); Assertions.assertEquals("4Gi", deployment.settings().resourceRequests().memory()); Assertions.assertEquals(2, deployment.instances().size()); File gzFile = downloadFile(PIGGYMETRICS_TAR_GZ_URL); deployment = app.deployments().define(deploymentName1) .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .withActivation() .create(); app.refresh(); Assertions.assertEquals(deploymentName1, app.activeDeploymentName()); Assertions.assertEquals("1", deployment.settings().resourceRequests().cpu()); Assertions.assertNotNull(deployment.getLogFileUrl()); Assertions.assertTrue(requestSuccess(app.url())); app.update() .withoutDefaultPublicEndpoint() .apply(); Assertions.assertFalse(app.isPublic()); app.deployments().deleteByName(deploymentName); Assertions.assertEquals(1, app.deployments().list().stream().count()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateCustomDomainWithSsl() throws Exception { String domainName = generateRandomResourceName("jsdkdemo-", 20) + ".com"; String certOrderName = generateRandomResourceName("cert", 15); String vaultName = generateRandomResourceName("vault", 15); String certName = generateRandomResourceName("cert", 15); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; Region region = Region.US_EAST; allowAllSSL(); String cerPassword = password(); String resourcePath = Paths.get(this.getClass().getResource("/session-records").toURI()).getParent().toString(); String cerPath = resourcePath + domainName + ".cer"; String pfxPath = resourcePath + domainName + ".pfx"; createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); appPlatformManager.resourceManager().resourceGroups().define(rgName) .withRegion(region) .create(); DnsZone dnsZone = dnsZoneManager.zones().define(domainName) .withExistingResourceGroup(rgName) .create(); AppServiceDomain domain = appServiceManager.domains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .withExistingDnsZone(dnsZone) .create(); Vault vault = keyVaultManager.vaults().define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(SPRING_CLOUD_SERVICE_OBJECT_ID) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(appPlatformManager.httpPipeline()) .buildClient(); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setPassword(cerPassword) .setEnabled(true) ); KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); String alias = Collections.list(store.aliases()).get(0); String thumbprint = printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .withCertificate("test", vault.vaultUri(), certName) .create(); service.apps().define(appName).withDefaultActiveDeployment().withDefaultPublicEndpoint().create(); SpringApp app = service.apps().getByName(appName); dnsZone.update() .withCNameRecordSet("www", app.fqdn()) .withCNameRecordSet("ssl", app.fqdn()) .apply(); app.update() .withoutDefaultPublicEndpoint() .withCustomDomain(String.format("www.%s", domainName)) .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); Assertions.assertTrue(app.customDomains().validate(String.format("www.%s", domainName)).isValid()); Assertions.assertTrue(requestSuccess(String.format("http: Assertions.assertTrue(requestSuccess(String.format("https: app.update() .withHttpsOnly() .withoutCustomDomain(String.format("www.%s", domainName)) .apply(); Assertions.assertTrue(checkRedirect(String.format("http: } @Test @DoNotRecord(skipInPlayback = true) private File downloadFile(String remoteFileUrl) throws Exception { String[] split = remoteFileUrl.split("/"); String filename = split[split.length - 1]; File downloaded = new File(filename); if (!downloaded.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(remoteFileUrl).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(downloaded)) { IOUtils.copy(inputStream, outputStream); } finally { connection.disconnect(); } } return downloaded; } private void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } private byte[] readAllBytes(InputStream inputStream) throws IOException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { byte[] data = new byte[4096]; while (true) { int size = inputStream.read(data); if (size > 0) { outputStream.write(data, 0, size); } else { return outputStream.toByteArray(); } } } } public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName, String dnsName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; if (dnsName != null) { List<String> args = new ArrayList<>(Arrays.asList(commandArgs)); args.add("-ext"); args.add("san=dns:" + dnsName); commandArgs = args.toArray(new String[0]); } cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!"".equals(error))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } private static final char[] HEX_CODE = "0123456789ABCDEF".toCharArray(); private static String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder(data.length * 2); for (byte b : data) { r.append(HEX_CODE[(b >> 4) & 0xF]); r.append(HEX_CODE[(b & 0xF)]); } return r.toString(); } }
class SpringCloudLiveOnlyTest extends AppPlatformTest { private static final String PIGGYMETRICS_CONFIG_URL = "https: private static final String GATEWAY_JAR_URL = "https: private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String PETCLINIC_CONFIG_URL = "https: private static final String PETCLINIC_GATEWAY_JAR_URL = "https: private static final String PETCLINIC_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_OBJECT_ID = "938df8e2-2b9d-40b1-940c-c75c33494239"; @Test @DoNotRecord(skipInPlayback = true) public void canCRUDDeployment() throws Exception { allowAllSSL(); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; String deploymentName = generateRandomResourceName("deploy", 15); String deploymentName1 = generateRandomResourceName("deploy", 15); Region region = Region.US_EAST; SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .create(); File jarFile = downloadFile(GATEWAY_JAR_URL); SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu(2) .withMemory(4) .withRuntime(RuntimeVersion.JAVA_11) .attach() .withDefaultPublicEndpoint() .create(); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); Assertions.assertTrue(requestSuccess(app.url())); SpringAppDeployment deployment = app.getActiveDeployment(); Assertions.assertEquals("2", deployment.settings().resourceRequests().cpu()); Assertions.assertEquals("4Gi", deployment.settings().resourceRequests().memory()); Assertions.assertEquals(2, deployment.instances().size()); File gzFile = downloadFile(PIGGYMETRICS_TAR_GZ_URL); deployment = app.deployments().define(deploymentName1) .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .withActivation() .create(); app.refresh(); Assertions.assertEquals(deploymentName1, app.activeDeploymentName()); Assertions.assertEquals("1", deployment.settings().resourceRequests().cpu()); Assertions.assertNotNull(deployment.getLogFileUrl()); Assertions.assertTrue(requestSuccess(app.url())); app.update() .withoutDefaultPublicEndpoint() .apply(); Assertions.assertFalse(app.isPublic()); app.deployments().deleteByName(deploymentName); Assertions.assertEquals(1, app.deployments().list().stream().count()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateCustomDomainWithSsl() throws Exception { String domainName = generateRandomResourceName("jsdkdemo-", 20) + ".com"; String certOrderName = generateRandomResourceName("cert", 15); String vaultName = generateRandomResourceName("vault", 15); String certName = generateRandomResourceName("cert", 15); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; Region region = Region.US_EAST; allowAllSSL(); String cerPassword = password(); String resourcePath = Paths.get(this.getClass().getResource("/session-records").toURI()).getParent().toString(); String cerPath = resourcePath + domainName + ".cer"; String pfxPath = resourcePath + domainName + ".pfx"; createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); appPlatformManager.resourceManager().resourceGroups().define(rgName) .withRegion(region) .create(); DnsZone dnsZone = dnsZoneManager.zones().define(domainName) .withExistingResourceGroup(rgName) .create(); AppServiceDomain domain = appServiceManager.domains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .withExistingDnsZone(dnsZone) .create(); Vault vault = keyVaultManager.vaults().define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(SPRING_CLOUD_SERVICE_OBJECT_ID) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(appPlatformManager.httpPipeline()) .buildClient(); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setPassword(cerPassword) .setEnabled(true) ); KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); String alias = Collections.list(store.aliases()).get(0); String thumbprint = printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .withCertificate("test", vault.vaultUri(), certName) .create(); service.apps().define(appName).withDefaultActiveDeployment().withDefaultPublicEndpoint().create(); SpringApp app = service.apps().getByName(appName); dnsZone.update() .withCNameRecordSet("www", app.fqdn()) .withCNameRecordSet("ssl", app.fqdn()) .apply(); app.update() .withoutDefaultPublicEndpoint() .withCustomDomain(String.format("www.%s", domainName)) .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); Assertions.assertTrue(app.customDomains().validate(String.format("www.%s", domainName)).isValid()); Assertions.assertTrue(requestSuccess(String.format("http: Assertions.assertTrue(requestSuccess(String.format("https: app.update() .withHttpsOnly() .withoutCustomDomain(String.format("www.%s", domainName)) .apply(); Assertions.assertTrue(checkRedirect(String.format("http: } @Test @DoNotRecord(skipInPlayback = true) private File downloadFile(String remoteFileUrl) throws Exception { String[] split = remoteFileUrl.split("/"); String filename = split[split.length - 1]; File downloaded = new File(filename); if (!downloaded.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(remoteFileUrl).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(downloaded)) { IOUtils.copy(inputStream, outputStream); } finally { connection.disconnect(); } } return downloaded; } private void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } private byte[] readAllBytes(InputStream inputStream) throws IOException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { byte[] data = new byte[4096]; while (true) { int size = inputStream.read(data); if (size > 0) { outputStream.write(data, 0, size); } else { return outputStream.toByteArray(); } } } } public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName, String dnsName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; if (dnsName != null) { List<String> args = new ArrayList<>(Arrays.asList(commandArgs)); args.add("-ext"); args.add("san=dns:" + dnsName); commandArgs = args.toArray(new String[0]); } cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!"".equals(error))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } private static final char[] HEX_CODE = "0123456789ABCDEF".toCharArray(); private static String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder(data.length * 2); for (byte b : data) { r.append(HEX_CODE[(b >> 4) & 0xF]); r.append(HEX_CODE[(b & 0xF)]); } return r.toString(); } }
Got it. I thought either regex or glob when hear pattern.
public void canCRUDEnterpriseTierDeployment() throws Exception { allowAllSSL(); File tarGzFile = downloadFile(PETCLINIC_TAR_GZ_URL); File jarFile = downloadFile(PETCLINIC_GATEWAY_JAR_URL); String serviceName = generateRandomResourceName("springsvc", 15); Region region = Region.US_EAST; List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service"); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .withEnterpriseTierSku() .withDefaultGitRepository(PETCLINIC_CONFIG_URL, "master", configFilePatterns) .create(); String deploymentName = generateRandomResourceName("deploy", 15); List<String> apiGatewayConfigFilePatterns = Arrays.asList("api-gateway"); String appName = "api-gateway"; SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu("500m") .withMemory("512Mi") .attach() .withDefaultPublicEndpoint() .withConfigurationServiceBinding() .create(); SpringAppDeployment deployment = app.deployments().getByName(deploymentName); Assertions.assertTrue(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); deployment.update() .withConfigFilePatterns(apiGatewayConfigFilePatterns) .apply(); deployment.refresh(); Assertions.assertFalse(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); String appName2 = "customers-service"; String module = "spring-petclinic-customers-service"; List<String> customerServiceConfigFilePatterns = Arrays.asList("customers-service"); SpringApp app2 = service.apps().define(appName2) .defineActiveDeployment(deploymentName) .withSourceCodeTarGzFile(tarGzFile, customerServiceConfigFilePatterns) .withTargetModule(module) .attach() .withConfigurationServiceBinding() .create(); Assertions.assertNull(app2.url()); SpringAppDeployment customersDeployment = app2.deployments().getByName(deploymentName); Assertions.assertEquals(customerServiceConfigFilePatterns, customersDeployment.configFilePatterns()); }
List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service");
public void canCRUDEnterpriseTierDeployment() throws Exception { allowAllSSL(); File tarGzFile = downloadFile(PETCLINIC_TAR_GZ_URL); File jarFile = downloadFile(PETCLINIC_GATEWAY_JAR_URL); String serviceName = generateRandomResourceName("springsvc", 15); Region region = Region.US_EAST; List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service"); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .withEnterpriseTierSku() .withDefaultGitRepository(PETCLINIC_CONFIG_URL, "master", configFilePatterns) .create(); String deploymentName = generateRandomResourceName("deploy", 15); List<String> apiGatewayConfigFilePatterns = Arrays.asList("api-gateway"); String appName = "api-gateway"; SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu("500m") .withMemory("512Mi") .attach() .withDefaultPublicEndpoint() .withConfigurationServiceBinding() .create(); SpringAppDeployment deployment = app.deployments().getByName(deploymentName); Assertions.assertTrue(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); deployment.update() .withConfigFilePatterns(apiGatewayConfigFilePatterns) .apply(); deployment.refresh(); Assertions.assertFalse(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); String appName2 = "customers-service"; String module = "spring-petclinic-customers-service"; List<String> customerServiceConfigFilePatterns = Arrays.asList("customers-service"); SpringApp app2 = service.apps().define(appName2) .defineActiveDeployment(deploymentName) .withSourceCodeTarGzFile(tarGzFile, customerServiceConfigFilePatterns) .withTargetModule(module) .attach() .withConfigurationServiceBinding() .create(); Assertions.assertNull(app2.url()); SpringAppDeployment customersDeployment = app2.deployments().getByName(deploymentName); Assertions.assertEquals(customerServiceConfigFilePatterns, customersDeployment.configFilePatterns()); }
class SpringCloudLiveOnlyTest extends AppPlatformTest { private static final String PIGGYMETRICS_CONFIG_URL = "https: private static final String GATEWAY_JAR_URL = "https: private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String PETCLINIC_CONFIG_URL = "https: private static final String PETCLINIC_GATEWAY_JAR_URL = "https: private static final String PETCLINIC_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_OBJECT_ID = "938df8e2-2b9d-40b1-940c-c75c33494239"; @Test @DoNotRecord(skipInPlayback = true) public void canCRUDDeployment() throws Exception { allowAllSSL(); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; String deploymentName = generateRandomResourceName("deploy", 15); String deploymentName1 = generateRandomResourceName("deploy", 15); Region region = Region.US_EAST; SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .create(); File jarFile = downloadFile(GATEWAY_JAR_URL); SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu(2) .withMemory(4) .withRuntime(RuntimeVersion.JAVA_11) .attach() .withDefaultPublicEndpoint() .create(); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); Assertions.assertTrue(requestSuccess(app.url())); SpringAppDeployment deployment = app.getActiveDeployment(); Assertions.assertEquals("2", deployment.settings().resourceRequests().cpu()); Assertions.assertEquals("4Gi", deployment.settings().resourceRequests().memory()); Assertions.assertEquals(2, deployment.instances().size()); File gzFile = downloadFile(PIGGYMETRICS_TAR_GZ_URL); deployment = app.deployments().define(deploymentName1) .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .withActivation() .create(); app.refresh(); Assertions.assertEquals(deploymentName1, app.activeDeploymentName()); Assertions.assertEquals("1", deployment.settings().resourceRequests().cpu()); Assertions.assertNotNull(deployment.getLogFileUrl()); Assertions.assertTrue(requestSuccess(app.url())); app.update() .withoutDefaultPublicEndpoint() .apply(); Assertions.assertFalse(app.isPublic()); app.deployments().deleteByName(deploymentName); Assertions.assertEquals(1, app.deployments().list().stream().count()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateCustomDomainWithSsl() throws Exception { String domainName = generateRandomResourceName("jsdkdemo-", 20) + ".com"; String certOrderName = generateRandomResourceName("cert", 15); String vaultName = generateRandomResourceName("vault", 15); String certName = generateRandomResourceName("cert", 15); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; Region region = Region.US_EAST; allowAllSSL(); String cerPassword = password(); String resourcePath = Paths.get(this.getClass().getResource("/session-records").toURI()).getParent().toString(); String cerPath = resourcePath + domainName + ".cer"; String pfxPath = resourcePath + domainName + ".pfx"; createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); appPlatformManager.resourceManager().resourceGroups().define(rgName) .withRegion(region) .create(); DnsZone dnsZone = dnsZoneManager.zones().define(domainName) .withExistingResourceGroup(rgName) .create(); AppServiceDomain domain = appServiceManager.domains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .withExistingDnsZone(dnsZone) .create(); Vault vault = keyVaultManager.vaults().define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(SPRING_CLOUD_SERVICE_OBJECT_ID) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(appPlatformManager.httpPipeline()) .buildClient(); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setPassword(cerPassword) .setEnabled(true) ); KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); String alias = Collections.list(store.aliases()).get(0); String thumbprint = printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .withCertificate("test", vault.vaultUri(), certName) .create(); service.apps().define(appName).withDefaultActiveDeployment().withDefaultPublicEndpoint().create(); SpringApp app = service.apps().getByName(appName); dnsZone.update() .withCNameRecordSet("www", app.fqdn()) .withCNameRecordSet("ssl", app.fqdn()) .apply(); app.update() .withoutDefaultPublicEndpoint() .withCustomDomain(String.format("www.%s", domainName)) .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); Assertions.assertTrue(app.customDomains().validate(String.format("www.%s", domainName)).isValid()); Assertions.assertTrue(requestSuccess(String.format("http: Assertions.assertTrue(requestSuccess(String.format("https: app.update() .withHttpsOnly() .withoutCustomDomain(String.format("www.%s", domainName)) .apply(); Assertions.assertTrue(checkRedirect(String.format("http: } @Test @DoNotRecord(skipInPlayback = true) private File downloadFile(String remoteFileUrl) throws Exception { String[] split = remoteFileUrl.split("/"); String filename = split[split.length - 1]; File downloaded = new File(filename); if (!downloaded.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(remoteFileUrl).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(downloaded)) { IOUtils.copy(inputStream, outputStream); } finally { connection.disconnect(); } } return downloaded; } private void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } private byte[] readAllBytes(InputStream inputStream) throws IOException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { byte[] data = new byte[4096]; while (true) { int size = inputStream.read(data); if (size > 0) { outputStream.write(data, 0, size); } else { return outputStream.toByteArray(); } } } } public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName, String dnsName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; if (dnsName != null) { List<String> args = new ArrayList<>(Arrays.asList(commandArgs)); args.add("-ext"); args.add("san=dns:" + dnsName); commandArgs = args.toArray(new String[0]); } cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!"".equals(error))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } private static final char[] HEX_CODE = "0123456789ABCDEF".toCharArray(); private static String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder(data.length * 2); for (byte b : data) { r.append(HEX_CODE[(b >> 4) & 0xF]); r.append(HEX_CODE[(b & 0xF)]); } return r.toString(); } }
class SpringCloudLiveOnlyTest extends AppPlatformTest { private static final String PIGGYMETRICS_CONFIG_URL = "https: private static final String GATEWAY_JAR_URL = "https: private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String PETCLINIC_CONFIG_URL = "https: private static final String PETCLINIC_GATEWAY_JAR_URL = "https: private static final String PETCLINIC_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_OBJECT_ID = "938df8e2-2b9d-40b1-940c-c75c33494239"; @Test @DoNotRecord(skipInPlayback = true) public void canCRUDDeployment() throws Exception { allowAllSSL(); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; String deploymentName = generateRandomResourceName("deploy", 15); String deploymentName1 = generateRandomResourceName("deploy", 15); Region region = Region.US_EAST; SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .create(); File jarFile = downloadFile(GATEWAY_JAR_URL); SpringApp app = service.apps().define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) .withCpu(2) .withMemory(4) .withRuntime(RuntimeVersion.JAVA_11) .attach() .withDefaultPublicEndpoint() .create(); Assertions.assertNotNull(app.url()); Assertions.assertNotNull(app.activeDeploymentName()); Assertions.assertEquals(1, app.deployments().list().stream().count()); Assertions.assertTrue(requestSuccess(app.url())); SpringAppDeployment deployment = app.getActiveDeployment(); Assertions.assertEquals("2", deployment.settings().resourceRequests().cpu()); Assertions.assertEquals("4Gi", deployment.settings().resourceRequests().memory()); Assertions.assertEquals(2, deployment.instances().size()); File gzFile = downloadFile(PIGGYMETRICS_TAR_GZ_URL); deployment = app.deployments().define(deploymentName1) .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .withActivation() .create(); app.refresh(); Assertions.assertEquals(deploymentName1, app.activeDeploymentName()); Assertions.assertEquals("1", deployment.settings().resourceRequests().cpu()); Assertions.assertNotNull(deployment.getLogFileUrl()); Assertions.assertTrue(requestSuccess(app.url())); app.update() .withoutDefaultPublicEndpoint() .apply(); Assertions.assertFalse(app.isPublic()); app.deployments().deleteByName(deploymentName); Assertions.assertEquals(1, app.deployments().list().stream().count()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateCustomDomainWithSsl() throws Exception { String domainName = generateRandomResourceName("jsdkdemo-", 20) + ".com"; String certOrderName = generateRandomResourceName("cert", 15); String vaultName = generateRandomResourceName("vault", 15); String certName = generateRandomResourceName("cert", 15); String serviceName = generateRandomResourceName("springsvc", 15); String appName = "gateway"; Region region = Region.US_EAST; allowAllSSL(); String cerPassword = password(); String resourcePath = Paths.get(this.getClass().getResource("/session-records").toURI()).getParent().toString(); String cerPath = resourcePath + domainName + ".cer"; String pfxPath = resourcePath + domainName + ".pfx"; createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); appPlatformManager.resourceManager().resourceGroups().define(rgName) .withRegion(region) .create(); DnsZone dnsZone = dnsZoneManager.zones().define(domainName) .withExistingResourceGroup(rgName) .create(); AppServiceDomain domain = appServiceManager.domains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .withExistingDnsZone(dnsZone) .create(); Vault vault = keyVaultManager.vaults().define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(SPRING_CLOUD_SERVICE_OBJECT_ID) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(appPlatformManager.httpPipeline()) .buildClient(); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setPassword(cerPassword) .setEnabled(true) ); KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); String alias = Collections.list(store.aliases()).get(0); String thumbprint = printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); SpringService service = appPlatformManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .withCertificate("test", vault.vaultUri(), certName) .create(); service.apps().define(appName).withDefaultActiveDeployment().withDefaultPublicEndpoint().create(); SpringApp app = service.apps().getByName(appName); dnsZone.update() .withCNameRecordSet("www", app.fqdn()) .withCNameRecordSet("ssl", app.fqdn()) .apply(); app.update() .withoutDefaultPublicEndpoint() .withCustomDomain(String.format("www.%s", domainName)) .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); Assertions.assertTrue(app.customDomains().validate(String.format("www.%s", domainName)).isValid()); Assertions.assertTrue(requestSuccess(String.format("http: Assertions.assertTrue(requestSuccess(String.format("https: app.update() .withHttpsOnly() .withoutCustomDomain(String.format("www.%s", domainName)) .apply(); Assertions.assertTrue(checkRedirect(String.format("http: } @Test @DoNotRecord(skipInPlayback = true) private File downloadFile(String remoteFileUrl) throws Exception { String[] split = remoteFileUrl.split("/"); String filename = split[split.length - 1]; File downloaded = new File(filename); if (!downloaded.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(remoteFileUrl).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(downloaded)) { IOUtils.copy(inputStream, outputStream); } finally { connection.disconnect(); } } return downloaded; } private void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } private byte[] readAllBytes(InputStream inputStream) throws IOException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { byte[] data = new byte[4096]; while (true) { int size = inputStream.read(data); if (size > 0) { outputStream.write(data, 0, size); } else { return outputStream.toByteArray(); } } } } public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName, String dnsName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; if (dnsName != null) { List<String> args = new ArrayList<>(Arrays.asList(commandArgs)); args.add("-ext"); args.add("san=dns:" + dnsName); commandArgs = args.toArray(new String[0]); } cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!"".equals(error))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } private static final char[] HEX_CODE = "0123456789ABCDEF".toCharArray(); private static String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder(data.length * 2); for (byte b : data) { r.append(HEX_CODE[(b >> 4) & 0xF]); r.append(HEX_CODE[(b & 0xF)]); } return r.toString(); } }
I assume it should be `ManagementException`? Use the `getBuildResultWithResponseAsync` for the `Response` instance that can be used for `ManagementException`.
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(buildResultInner -> { BuildResultProvisioningState state = buildResultInner.properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else return Mono.error(new RuntimeException("build failed")); }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( manager().serviceClient().getDefaultPollInterval()))))); }
} else return Mono.error(new RuntimeException("build failed"));
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { AtomicLong pollCount = new AtomicLong(); Duration pollDuration = manager().serviceClient().getDefaultPollInterval(); return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultWithResponseAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(response -> { if (pollDuration.multipliedBy(pollCount.get()).compareTo(MAX_BUILD_TIMEOUT) < 0) { BuildResultProvisioningState state = response.getValue().properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return Mono.error(new ManagementException(String.format("Build failed for file: %s, buildId: %s", file.getName(), buildId), new HttpResponseImpl<>(response, client.getSerializerAdapter()))); } } else { return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", file.getName(), buildId), null)); } }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> { pollCount.set(index); return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); }))); }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } @SuppressWarnings("BlockingMethodInNonBlockingContext") private class HttpResponseImpl<T> extends HttpResponse { private final Response<T> response; private final SerializerAdapter serializerAdapter; protected HttpResponseImpl(Response<T> response, SerializerAdapter serializerAdapter) { super(response.getRequest()); this.response = response; this.serializerAdapter = serializerAdapter; } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public String getHeaderValue(String header) { return response.getHeaders().getValue(header); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { try { return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } } @Override public Mono<byte[]> getBodyAsByteArray() { try { return Mono.just(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON)); } catch (IOException e) { return Mono.empty(); } } @Override public Mono<String> getBodyAsString() { return Mono.just(serializerAdapter.serializeRaw(response.getValue())); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsString(); } } }
Do we need a timeout? A hour is also fine but I guess we need one? Can be added later.
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(buildResultInner -> { BuildResultProvisioningState state = buildResultInner.properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else return Mono.error(new RuntimeException("build failed")); }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( manager().serviceClient().getDefaultPollInterval()))))); }
}).repeatWhenEmpty(
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { AtomicLong pollCount = new AtomicLong(); Duration pollDuration = manager().serviceClient().getDefaultPollInterval(); return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultWithResponseAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(response -> { if (pollDuration.multipliedBy(pollCount.get()).compareTo(MAX_BUILD_TIMEOUT) < 0) { BuildResultProvisioningState state = response.getValue().properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return Mono.error(new ManagementException(String.format("Build failed for file: %s, buildId: %s", file.getName(), buildId), new HttpResponseImpl<>(response, client.getSerializerAdapter()))); } } else { return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", file.getName(), buildId), null)); } }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> { pollCount.set(index); return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); }))); }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } @SuppressWarnings("BlockingMethodInNonBlockingContext") private class HttpResponseImpl<T> extends HttpResponse { private final Response<T> response; private final SerializerAdapter serializerAdapter; protected HttpResponseImpl(Response<T> response, SerializerAdapter serializerAdapter) { super(response.getRequest()); this.response = response; this.serializerAdapter = serializerAdapter; } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public String getHeaderValue(String header) { return response.getHeaders().getValue(header); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { try { return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } } @Override public Mono<byte[]> getBodyAsByteArray() { try { return Mono.just(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON)); } catch (IOException e) { return Mono.empty(); } } @Override public Mono<String> getBodyAsString() { return Mono.just(serializerAdapter.serializeRaw(response.getValue())); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsString(); } } }
Could this become `return setBody(BinaryData.fromString(content));`
public HttpRequest setBody(String content) { this.body = BinaryData.fromString(content); setContentLength(this.body.getLength()); return this; }
return this;
public HttpRequest setBody(String content) { return setBody(BinaryData.fromString(content)); }
class HttpRequest { private static final ClientLogger LOGGER = new ClientLogger(HttpRequest.class); private HttpMethod httpMethod; private URL url; private HttpHeaders headers; private BinaryData body; /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to */ public HttpRequest(HttpMethod httpMethod, URL url) { this(httpMethod, url, new HttpHeaders(), (BinaryData) null); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = httpMethod; setUrl(url); this.headers = new HttpHeaders(); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(body))); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, BinaryData body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(body); } /** * Get the request method. * * @return the request method */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Set the request method. * * @param httpMethod the request method * @return this HttpRequest */ public HttpRequest setHttpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } /** * Get the target address. * * @return the target address */ public URL getUrl() { return url; } /** * Set the target address to send the request to. * * @param url target address as {@link URL} * @return this HttpRequest */ public HttpRequest setUrl(URL url) { this.url = url; return this; } /** * Set the target address to send the request to. * * @param url target address as a String * @return this HttpRequest * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); } return this; } /** * Get the request headers. * * @return headers to be sent */ public HttpHeaders getHeaders() { return headers; } /** * Set the request headers. * * @param headers the set of headers * @return this HttpRequest */ public HttpRequest setHeaders(HttpHeaders headers) { this.headers = headers; return this; } /** * Set a request header, replacing any existing value. A null for {@code value} will remove the header if one with * matching name exists. * * @param name the header name * @param value the header value * @return this HttpRequest */ public HttpRequest setHeader(String name, String value) { headers.set(name, value); return this; } /** * Get the request content. * * @return the content to be send */ public Flux<ByteBuffer> getBody() { return body == null ? null : body.toFluxByteBuffer(); } /** * Get the request content. * * @return the content to be send */ public BinaryData getBodyAsBinaryData() { return body; } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(byte[] content) { setContentLength(content.length); this.body = BinaryData.fromBytes(content); return this; } /** * Set request content. * <p> * Caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(Flux<ByteBuffer> content) { if (content != null) { setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(content))); } else { this.body = null; } return this; } /** * Set request content. * <p> * If provided content has known length, i.e. {@link BinaryData * Content-Length header is updated. Otherwise, * if provided content has unknown length, i.e. {@link BinaryData * the caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(BinaryData content) { this.body = content; if (content != null && content.getLength() != null) { setContentLength(content.getLength()); } return this; } private void setContentLength(long contentLength) { headers.set("Content-Length", String.valueOf(contentLength)); } /** * Creates a copy of the request. * * The main purpose of this is so that this HttpRequest can be changed and the resulting HttpRequest can be a * backup. This means that the cloned HttpHeaders and body must not be able to change from side effects of this * HttpRequest. * * @return a new HTTP request instance with cloned instances of all mutable properties. */ public HttpRequest copy() { final HttpHeaders bufferedHeaders = new HttpHeaders(headers); return new HttpRequest(httpMethod, url, bufferedHeaders, body); } }
class HttpRequest { private static final ClientLogger LOGGER = new ClientLogger(HttpRequest.class); private HttpMethod httpMethod; private URL url; private HttpHeaders headers; private BinaryData body; /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to */ public HttpRequest(HttpMethod httpMethod, URL url) { this(httpMethod, url, new HttpHeaders(), (BinaryData) null); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = httpMethod; setUrl(url); this.headers = new HttpHeaders(); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(body))); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, BinaryData body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(body); } /** * Get the request method. * * @return the request method */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Set the request method. * * @param httpMethod the request method * @return this HttpRequest */ public HttpRequest setHttpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } /** * Get the target address. * * @return the target address */ public URL getUrl() { return url; } /** * Set the target address to send the request to. * * @param url target address as {@link URL} * @return this HttpRequest */ public HttpRequest setUrl(URL url) { this.url = url; return this; } /** * Set the target address to send the request to. * * @param url target address as a String * @return this HttpRequest * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); } return this; } /** * Get the request headers. * * @return headers to be sent */ public HttpHeaders getHeaders() { return headers; } /** * Set the request headers. * * @param headers the set of headers * @return this HttpRequest */ public HttpRequest setHeaders(HttpHeaders headers) { this.headers = headers; return this; } /** * Set a request header, replacing any existing value. A null for {@code value} will remove the header if one with * matching name exists. * * @param name the header name * @param value the header value * @return this HttpRequest */ public HttpRequest setHeader(String name, String value) { headers.set(name, value); return this; } /** * Get the request content. * * @return the content to be sent */ public Flux<ByteBuffer> getBody() { return body == null ? null : body.toFluxByteBuffer(); } /** * Get the request content. * * @return the content to be sent */ public BinaryData getBodyAsBinaryData() { return body; } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(byte[] content) { return setBody(BinaryData.fromBytes(content)); } /** * Set request content. * <p> * Caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(Flux<ByteBuffer> content) { if (content != null) { this.body = BinaryDataHelper.createBinaryData(new FluxByteBufferContent(content)); } else { this.body = null; } return this; } /** * Set request content. * <p> * If provided content has known length, i.e. {@link BinaryData * Content-Length header is updated. Otherwise, * if provided content has unknown length, i.e. {@link BinaryData * the caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(BinaryData content) { this.body = content; if (content != null && content.getLength() != null) { setContentLength(content.getLength()); } return this; } private void setContentLength(long contentLength) { headers.set("Content-Length", String.valueOf(contentLength)); } /** * Creates a copy of the request. * * The main purpose of this is so that this HttpRequest can be changed and the resulting HttpRequest can be a * backup. This means that the cloned HttpHeaders and body must not be able to change from side effects of this * HttpRequest. * * @return a new HTTP request instance with cloned instances of all mutable properties. */ public HttpRequest copy() { final HttpHeaders bufferedHeaders = new HttpHeaders(headers); return new HttpRequest(httpMethod, url, bufferedHeaders, body); } }
OK.
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(buildResultInner -> { BuildResultProvisioningState state = buildResultInner.properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else return Mono.error(new RuntimeException("build failed")); }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( manager().serviceClient().getDefaultPollInterval()))))); }
} else return Mono.error(new RuntimeException("build failed"));
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { AtomicLong pollCount = new AtomicLong(); Duration pollDuration = manager().serviceClient().getDefaultPollInterval(); return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultWithResponseAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(response -> { if (pollDuration.multipliedBy(pollCount.get()).compareTo(MAX_BUILD_TIMEOUT) < 0) { BuildResultProvisioningState state = response.getValue().properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return Mono.error(new ManagementException(String.format("Build failed for file: %s, buildId: %s", file.getName(), buildId), new HttpResponseImpl<>(response, client.getSerializerAdapter()))); } } else { return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", file.getName(), buildId), null)); } }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> { pollCount.set(index); return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); }))); }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } @SuppressWarnings("BlockingMethodInNonBlockingContext") private class HttpResponseImpl<T> extends HttpResponse { private final Response<T> response; private final SerializerAdapter serializerAdapter; protected HttpResponseImpl(Response<T> response, SerializerAdapter serializerAdapter) { super(response.getRequest()); this.response = response; this.serializerAdapter = serializerAdapter; } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public String getHeaderValue(String header) { return response.getHeaders().getValue(header); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { try { return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } } @Override public Mono<byte[]> getBodyAsByteArray() { try { return Mono.just(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON)); } catch (IOException e) { return Mono.empty(); } } @Override public Mono<String> getBodyAsString() { return Mono.just(serializerAdapter.serializeRaw(response.getValue())); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsString(); } } }
Sure, I'll add timeout.
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(buildResultInner -> { BuildResultProvisioningState state = buildResultInner.properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else return Mono.error(new RuntimeException("build failed")); }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( manager().serviceClient().getDefaultPollInterval()))))); }
}).repeatWhenEmpty(
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { AtomicLong pollCount = new AtomicLong(); Duration pollDuration = manager().serviceClient().getDefaultPollInterval(); return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(buildId -> manager().serviceClient().getBuildServices() .getBuildResultWithResponseAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(response -> { if (pollDuration.multipliedBy(pollCount.get()).compareTo(MAX_BUILD_TIMEOUT) < 0) { BuildResultProvisioningState state = response.getValue().properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return Mono.error(new ManagementException(String.format("Build failed for file: %s, buildId: %s", file.getName(), buildId), new HttpResponseImpl<>(response, client.getSerializerAdapter()))); } } else { return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", file.getName(), buildId), null)); } }).repeatWhenEmpty( longFlux -> longFlux .flatMap( index -> { pollCount.set(index); return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); }))); }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } @SuppressWarnings("BlockingMethodInNonBlockingContext") private class HttpResponseImpl<T> extends HttpResponse { private final Response<T> response; private final SerializerAdapter serializerAdapter; protected HttpResponseImpl(Response<T> response, SerializerAdapter serializerAdapter) { super(response.getRequest()); this.response = response; this.serializerAdapter = serializerAdapter; } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public String getHeaderValue(String header) { return response.getHeaders().getValue(header); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { try { return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } } @Override public Mono<byte[]> getBodyAsByteArray() { try { return Mono.just(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON)); } catch (IOException e) { return Mono.empty(); } } @Override public Mono<String> getBodyAsString() { return Mono.just(serializerAdapter.serializeRaw(response.getValue())); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsString(); } } }
let's merge it. but we should discuss this issue during api review.
public ShareFileRenameOptions setHeaders(ShareFileHttpHeaders headers) { if (headers.getCacheControl() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("cache control is not supported on this api")); } if (headers.getContentDisposition() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content disposition is not supported on this api")); } if (headers.getContentEncoding() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content encoding is not supported on this api")); } if (headers.getContentLanguage() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content language is not supported on this api")); } if (headers.getContentMd5() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content md5 is not supported on this api")); } this.headers = headers; return this; }
return this;
public ShareFileRenameOptions setHeaders(ShareFileHttpHeaders headers) { if (headers.getCacheControl() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("cache control is not supported on this api")); } if (headers.getContentDisposition() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content disposition is not supported on this api")); } if (headers.getContentEncoding() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content encoding is not supported on this api")); } if (headers.getContentLanguage() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content language is not supported on this api")); } if (headers.getContentMd5() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content md5 is not supported on this api")); } this.headers = headers; return this; }
class ShareFileRenameOptions { private static final ClientLogger LOGGER = new ClientLogger(ShareFileRenameOptions.class); private final String destinationPath; private Boolean replaceIfExists; private Boolean ignoreReadOnly; private ShareRequestConditions sourceRequestConditions; private ShareRequestConditions destinationRequestConditions; private String filePermission; private FileSmbProperties smbProperties; private Map<String, String> metadata; private ShareFileHttpHeaders headers; /** * Creates a {@code ShareFileRenameOptions} object. * * @param destinationPath Relative path from the share to rename the file to. */ public ShareFileRenameOptions(String destinationPath) { StorageImplUtils.assertNotNull("destinationPath", destinationPath); this.destinationPath = destinationPath; } /** * @return The path to which the file should be renamed. */ public String getDestinationPath() { return destinationPath; } /** * @return A boolean value which, if the destination file already exists, determines whether this * request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. * If not provided or if false and the destination file does exist, the request will not overwrite the destination * file. If provided and the destination file doesn’t exist, the rename will succeed. */ public Boolean getReplaceIfExists() { return replaceIfExists; } /** * @param replaceIfExists A boolean value which, if the destination file already exists, determines whether this * request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. * If not provided or if false and the destination file does exist, the request will not overwrite the destination * file. If provided and the destination file doesn’t exist, the rename will succeed. * @return The updated options. */ public ShareFileRenameOptions setReplaceIfExists(Boolean replaceIfExists) { this.replaceIfExists = replaceIfExists; return this; } /** * @return A boolean value that specifies whether the ReadOnly attribute on a preexisting destination file should be * respected. If true, the rename will succeed, otherwise, a previous file at the destination with the ReadOnly * attribute set will cause the rename to fail. */ public Boolean isIgnoreReadOnly() { return ignoreReadOnly; } /** * @param ignoreReadOnly A boolean value that specifies whether the ReadOnly attribute on a preexisting destination * file should be respected. If true, the rename will succeed, otherwise, a previous file at the destination with * the ReadOnly attribute set will cause the rename to fail. * @return The updated options. */ public ShareFileRenameOptions setIgnoreReadOnly(Boolean ignoreReadOnly) { this.ignoreReadOnly = ignoreReadOnly; return this; } /** * @return Source request conditions. This parameter is only applicable if the source is a file. */ public ShareRequestConditions getSourceRequestConditions() { return sourceRequestConditions; } /** * @param sourceRequestConditions Source request conditions. This parameter is only applicable if the source is a * file. * @return The updated options. */ public ShareFileRenameOptions setSourceRequestConditions(ShareRequestConditions sourceRequestConditions) { this.sourceRequestConditions = sourceRequestConditions; return this; } /** * @return The destination request conditions. */ public ShareRequestConditions getDestinationRequestConditions() { return destinationRequestConditions; } /** * @param destinationRequestConditions The destination request conditions. * @return The updated options. */ public ShareFileRenameOptions setDestinationRequestConditions(ShareRequestConditions destinationRequestConditions) { this.destinationRequestConditions = destinationRequestConditions; return this; } /** * @return Optional file permission to set on the destination file or directory. The value in SmbProperties will be * ignored. */ public String getFilePermission() { return filePermission; } /** * @param filePermission Optional file permission to set on the destination file or directory. The value in * SmbProperties will be ignored. * @return The updated options. */ public ShareFileRenameOptions setFilePermission(String filePermission) { this.filePermission = filePermission; return this; } /** * @return Optional SMB properties to set on the destination file or directory. The only properties that are * considered are file attributes, file creation time, file last write time, and file permission key. The rest are * ignored. */ public FileSmbProperties getSmbProperties() { return smbProperties; } /** * @param smbProperties Optional SMB properties to set on the destination file or directory. The only properties * that are considered are file attributes, file creation time, file last write time, and file permission key. The * rest are ignored. * @return The updated options. */ public ShareFileRenameOptions setSmbProperties(FileSmbProperties smbProperties) { this.smbProperties = smbProperties; return this; } /** * @return The metadata to associate with the renamed file. */ public Map<String, String> getMetadata() { return this.metadata; } /** * @param metadata The metadata to associate with the renamed file. * @return The updated options. */ public ShareFileRenameOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Gets the {@link ShareFileHttpHeaders}. Currently, only content type is respected. Others are ignored. * * @return The {@link ShareFileHttpHeaders}. */ public ShareFileHttpHeaders getHeaders() { return this.headers; } /** * Sets the {@link ShareFileHttpHeaders}. Currently, only content type is respected. This method will throw if * others are set. * * @param headers {@link ShareFileHttpHeaders} * @return The updated options. * @throws IllegalArgumentException If headers besides content type are set, this method will throw. */ }
class ShareFileRenameOptions { private static final ClientLogger LOGGER = new ClientLogger(ShareFileRenameOptions.class); private final String destinationPath; private Boolean replaceIfExists; private Boolean ignoreReadOnly; private ShareRequestConditions sourceRequestConditions; private ShareRequestConditions destinationRequestConditions; private String filePermission; private FileSmbProperties smbProperties; private Map<String, String> metadata; private ShareFileHttpHeaders headers; /** * Creates a {@code ShareFileRenameOptions} object. * * @param destinationPath Relative path from the share to rename the file to. */ public ShareFileRenameOptions(String destinationPath) { StorageImplUtils.assertNotNull("destinationPath", destinationPath); this.destinationPath = destinationPath; } /** * @return The path to which the file should be renamed. */ public String getDestinationPath() { return destinationPath; } /** * @return A boolean value which, if the destination file already exists, determines whether this * request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. * If not provided or if false and the destination file does exist, the request will not overwrite the destination * file. If provided and the destination file doesn’t exist, the rename will succeed. */ public Boolean getReplaceIfExists() { return replaceIfExists; } /** * @param replaceIfExists A boolean value which, if the destination file already exists, determines whether this * request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. * If not provided or if false and the destination file does exist, the request will not overwrite the destination * file. If provided and the destination file doesn’t exist, the rename will succeed. * @return The updated options. */ public ShareFileRenameOptions setReplaceIfExists(Boolean replaceIfExists) { this.replaceIfExists = replaceIfExists; return this; } /** * @return A boolean value that specifies whether the ReadOnly attribute on a preexisting destination file should be * respected. If true, the rename will succeed, otherwise, a previous file at the destination with the ReadOnly * attribute set will cause the rename to fail. */ public Boolean isIgnoreReadOnly() { return ignoreReadOnly; } /** * @param ignoreReadOnly A boolean value that specifies whether the ReadOnly attribute on a preexisting destination * file should be respected. If true, the rename will succeed, otherwise, a previous file at the destination with * the ReadOnly attribute set will cause the rename to fail. * @return The updated options. */ public ShareFileRenameOptions setIgnoreReadOnly(Boolean ignoreReadOnly) { this.ignoreReadOnly = ignoreReadOnly; return this; } /** * @return Source request conditions. This parameter is only applicable if the source is a file. */ public ShareRequestConditions getSourceRequestConditions() { return sourceRequestConditions; } /** * @param sourceRequestConditions Source request conditions. This parameter is only applicable if the source is a * file. * @return The updated options. */ public ShareFileRenameOptions setSourceRequestConditions(ShareRequestConditions sourceRequestConditions) { this.sourceRequestConditions = sourceRequestConditions; return this; } /** * @return The destination request conditions. */ public ShareRequestConditions getDestinationRequestConditions() { return destinationRequestConditions; } /** * @param destinationRequestConditions The destination request conditions. * @return The updated options. */ public ShareFileRenameOptions setDestinationRequestConditions(ShareRequestConditions destinationRequestConditions) { this.destinationRequestConditions = destinationRequestConditions; return this; } /** * @return Optional file permission to set on the destination file or directory. The value in SmbProperties will be * ignored. */ public String getFilePermission() { return filePermission; } /** * @param filePermission Optional file permission to set on the destination file or directory. The value in * SmbProperties will be ignored. * @return The updated options. */ public ShareFileRenameOptions setFilePermission(String filePermission) { this.filePermission = filePermission; return this; } /** * @return Optional SMB properties to set on the destination file or directory. The only properties that are * considered are file attributes, file creation time, file last write time, and file permission key. The rest are * ignored. */ public FileSmbProperties getSmbProperties() { return smbProperties; } /** * @param smbProperties Optional SMB properties to set on the destination file or directory. The only properties * that are considered are file attributes, file creation time, file last write time, and file permission key. The * rest are ignored. * @return The updated options. */ public ShareFileRenameOptions setSmbProperties(FileSmbProperties smbProperties) { this.smbProperties = smbProperties; return this; } /** * @return The metadata to associate with the renamed file. */ public Map<String, String> getMetadata() { return this.metadata; } /** * @param metadata The metadata to associate with the renamed file. * @return The updated options. */ public ShareFileRenameOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Gets the {@link ShareFileHttpHeaders}. Currently, only content type is respected. Others are ignored. * * @return The {@link ShareFileHttpHeaders}. */ public ShareFileHttpHeaders getHeaders() { return this.headers; } /** * Sets the {@link ShareFileHttpHeaders}. Currently, only content type is respected. This method will throw if * others are set. * * @param headers {@link ShareFileHttpHeaders} * @return The updated options. * @throws IllegalArgumentException If headers besides content type are set, this method will throw. */ }
I vote we make ContentType a property on ShareFileRenameOptions
public ShareFileRenameOptions setHeaders(ShareFileHttpHeaders headers) { if (headers.getCacheControl() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("cache control is not supported on this api")); } if (headers.getContentDisposition() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content disposition is not supported on this api")); } if (headers.getContentEncoding() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content encoding is not supported on this api")); } if (headers.getContentLanguage() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content language is not supported on this api")); } if (headers.getContentMd5() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content md5 is not supported on this api")); } this.headers = headers; return this; }
return this;
public ShareFileRenameOptions setHeaders(ShareFileHttpHeaders headers) { if (headers.getCacheControl() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("cache control is not supported on this api")); } if (headers.getContentDisposition() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content disposition is not supported on this api")); } if (headers.getContentEncoding() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content encoding is not supported on this api")); } if (headers.getContentLanguage() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content language is not supported on this api")); } if (headers.getContentMd5() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("content md5 is not supported on this api")); } this.headers = headers; return this; }
class ShareFileRenameOptions { private static final ClientLogger LOGGER = new ClientLogger(ShareFileRenameOptions.class); private final String destinationPath; private Boolean replaceIfExists; private Boolean ignoreReadOnly; private ShareRequestConditions sourceRequestConditions; private ShareRequestConditions destinationRequestConditions; private String filePermission; private FileSmbProperties smbProperties; private Map<String, String> metadata; private ShareFileHttpHeaders headers; /** * Creates a {@code ShareFileRenameOptions} object. * * @param destinationPath Relative path from the share to rename the file to. */ public ShareFileRenameOptions(String destinationPath) { StorageImplUtils.assertNotNull("destinationPath", destinationPath); this.destinationPath = destinationPath; } /** * @return The path to which the file should be renamed. */ public String getDestinationPath() { return destinationPath; } /** * @return A boolean value which, if the destination file already exists, determines whether this * request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. * If not provided or if false and the destination file does exist, the request will not overwrite the destination * file. If provided and the destination file doesn’t exist, the rename will succeed. */ public Boolean getReplaceIfExists() { return replaceIfExists; } /** * @param replaceIfExists A boolean value which, if the destination file already exists, determines whether this * request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. * If not provided or if false and the destination file does exist, the request will not overwrite the destination * file. If provided and the destination file doesn’t exist, the rename will succeed. * @return The updated options. */ public ShareFileRenameOptions setReplaceIfExists(Boolean replaceIfExists) { this.replaceIfExists = replaceIfExists; return this; } /** * @return A boolean value that specifies whether the ReadOnly attribute on a preexisting destination file should be * respected. If true, the rename will succeed, otherwise, a previous file at the destination with the ReadOnly * attribute set will cause the rename to fail. */ public Boolean isIgnoreReadOnly() { return ignoreReadOnly; } /** * @param ignoreReadOnly A boolean value that specifies whether the ReadOnly attribute on a preexisting destination * file should be respected. If true, the rename will succeed, otherwise, a previous file at the destination with * the ReadOnly attribute set will cause the rename to fail. * @return The updated options. */ public ShareFileRenameOptions setIgnoreReadOnly(Boolean ignoreReadOnly) { this.ignoreReadOnly = ignoreReadOnly; return this; } /** * @return Source request conditions. This parameter is only applicable if the source is a file. */ public ShareRequestConditions getSourceRequestConditions() { return sourceRequestConditions; } /** * @param sourceRequestConditions Source request conditions. This parameter is only applicable if the source is a * file. * @return The updated options. */ public ShareFileRenameOptions setSourceRequestConditions(ShareRequestConditions sourceRequestConditions) { this.sourceRequestConditions = sourceRequestConditions; return this; } /** * @return The destination request conditions. */ public ShareRequestConditions getDestinationRequestConditions() { return destinationRequestConditions; } /** * @param destinationRequestConditions The destination request conditions. * @return The updated options. */ public ShareFileRenameOptions setDestinationRequestConditions(ShareRequestConditions destinationRequestConditions) { this.destinationRequestConditions = destinationRequestConditions; return this; } /** * @return Optional file permission to set on the destination file or directory. The value in SmbProperties will be * ignored. */ public String getFilePermission() { return filePermission; } /** * @param filePermission Optional file permission to set on the destination file or directory. The value in * SmbProperties will be ignored. * @return The updated options. */ public ShareFileRenameOptions setFilePermission(String filePermission) { this.filePermission = filePermission; return this; } /** * @return Optional SMB properties to set on the destination file or directory. The only properties that are * considered are file attributes, file creation time, file last write time, and file permission key. The rest are * ignored. */ public FileSmbProperties getSmbProperties() { return smbProperties; } /** * @param smbProperties Optional SMB properties to set on the destination file or directory. The only properties * that are considered are file attributes, file creation time, file last write time, and file permission key. The * rest are ignored. * @return The updated options. */ public ShareFileRenameOptions setSmbProperties(FileSmbProperties smbProperties) { this.smbProperties = smbProperties; return this; } /** * @return The metadata to associate with the renamed file. */ public Map<String, String> getMetadata() { return this.metadata; } /** * @param metadata The metadata to associate with the renamed file. * @return The updated options. */ public ShareFileRenameOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Gets the {@link ShareFileHttpHeaders}. Currently, only content type is respected. Others are ignored. * * @return The {@link ShareFileHttpHeaders}. */ public ShareFileHttpHeaders getHeaders() { return this.headers; } /** * Sets the {@link ShareFileHttpHeaders}. Currently, only content type is respected. This method will throw if * others are set. * * @param headers {@link ShareFileHttpHeaders} * @return The updated options. * @throws IllegalArgumentException If headers besides content type are set, this method will throw. */ }
class ShareFileRenameOptions { private static final ClientLogger LOGGER = new ClientLogger(ShareFileRenameOptions.class); private final String destinationPath; private Boolean replaceIfExists; private Boolean ignoreReadOnly; private ShareRequestConditions sourceRequestConditions; private ShareRequestConditions destinationRequestConditions; private String filePermission; private FileSmbProperties smbProperties; private Map<String, String> metadata; private ShareFileHttpHeaders headers; /** * Creates a {@code ShareFileRenameOptions} object. * * @param destinationPath Relative path from the share to rename the file to. */ public ShareFileRenameOptions(String destinationPath) { StorageImplUtils.assertNotNull("destinationPath", destinationPath); this.destinationPath = destinationPath; } /** * @return The path to which the file should be renamed. */ public String getDestinationPath() { return destinationPath; } /** * @return A boolean value which, if the destination file already exists, determines whether this * request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. * If not provided or if false and the destination file does exist, the request will not overwrite the destination * file. If provided and the destination file doesn’t exist, the rename will succeed. */ public Boolean getReplaceIfExists() { return replaceIfExists; } /** * @param replaceIfExists A boolean value which, if the destination file already exists, determines whether this * request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. * If not provided or if false and the destination file does exist, the request will not overwrite the destination * file. If provided and the destination file doesn’t exist, the rename will succeed. * @return The updated options. */ public ShareFileRenameOptions setReplaceIfExists(Boolean replaceIfExists) { this.replaceIfExists = replaceIfExists; return this; } /** * @return A boolean value that specifies whether the ReadOnly attribute on a preexisting destination file should be * respected. If true, the rename will succeed, otherwise, a previous file at the destination with the ReadOnly * attribute set will cause the rename to fail. */ public Boolean isIgnoreReadOnly() { return ignoreReadOnly; } /** * @param ignoreReadOnly A boolean value that specifies whether the ReadOnly attribute on a preexisting destination * file should be respected. If true, the rename will succeed, otherwise, a previous file at the destination with * the ReadOnly attribute set will cause the rename to fail. * @return The updated options. */ public ShareFileRenameOptions setIgnoreReadOnly(Boolean ignoreReadOnly) { this.ignoreReadOnly = ignoreReadOnly; return this; } /** * @return Source request conditions. This parameter is only applicable if the source is a file. */ public ShareRequestConditions getSourceRequestConditions() { return sourceRequestConditions; } /** * @param sourceRequestConditions Source request conditions. This parameter is only applicable if the source is a * file. * @return The updated options. */ public ShareFileRenameOptions setSourceRequestConditions(ShareRequestConditions sourceRequestConditions) { this.sourceRequestConditions = sourceRequestConditions; return this; } /** * @return The destination request conditions. */ public ShareRequestConditions getDestinationRequestConditions() { return destinationRequestConditions; } /** * @param destinationRequestConditions The destination request conditions. * @return The updated options. */ public ShareFileRenameOptions setDestinationRequestConditions(ShareRequestConditions destinationRequestConditions) { this.destinationRequestConditions = destinationRequestConditions; return this; } /** * @return Optional file permission to set on the destination file or directory. The value in SmbProperties will be * ignored. */ public String getFilePermission() { return filePermission; } /** * @param filePermission Optional file permission to set on the destination file or directory. The value in * SmbProperties will be ignored. * @return The updated options. */ public ShareFileRenameOptions setFilePermission(String filePermission) { this.filePermission = filePermission; return this; } /** * @return Optional SMB properties to set on the destination file or directory. The only properties that are * considered are file attributes, file creation time, file last write time, and file permission key. The rest are * ignored. */ public FileSmbProperties getSmbProperties() { return smbProperties; } /** * @param smbProperties Optional SMB properties to set on the destination file or directory. The only properties * that are considered are file attributes, file creation time, file last write time, and file permission key. The * rest are ignored. * @return The updated options. */ public ShareFileRenameOptions setSmbProperties(FileSmbProperties smbProperties) { this.smbProperties = smbProperties; return this; } /** * @return The metadata to associate with the renamed file. */ public Map<String, String> getMetadata() { return this.metadata; } /** * @param metadata The metadata to associate with the renamed file. * @return The updated options. */ public ShareFileRenameOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Gets the {@link ShareFileHttpHeaders}. Currently, only content type is respected. Others are ignored. * * @return The {@link ShareFileHttpHeaders}. */ public ShareFileHttpHeaders getHeaders() { return this.headers; } /** * Sets the {@link ShareFileHttpHeaders}. Currently, only content type is respected. This method will throw if * others are set. * * @param headers {@link ShareFileHttpHeaders} * @return The updated options. * @throws IllegalArgumentException If headers besides content type are set, this method will throw. */ }
Same statement as above where this could just call into the `setBody(BinaryData)` method
public HttpRequest setBody(byte[] content) { setContentLength(content.length); this.body = BinaryData.fromBytes(content); return this; }
return this;
public HttpRequest setBody(byte[] content) { return setBody(BinaryData.fromBytes(content)); }
class HttpRequest { private static final ClientLogger LOGGER = new ClientLogger(HttpRequest.class); private HttpMethod httpMethod; private URL url; private HttpHeaders headers; private BinaryData body; /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to */ public HttpRequest(HttpMethod httpMethod, URL url) { this(httpMethod, url, new HttpHeaders(), (BinaryData) null); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = httpMethod; setUrl(url); this.headers = new HttpHeaders(); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(body))); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, BinaryData body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(body); } /** * Get the request method. * * @return the request method */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Set the request method. * * @param httpMethod the request method * @return this HttpRequest */ public HttpRequest setHttpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } /** * Get the target address. * * @return the target address */ public URL getUrl() { return url; } /** * Set the target address to send the request to. * * @param url target address as {@link URL} * @return this HttpRequest */ public HttpRequest setUrl(URL url) { this.url = url; return this; } /** * Set the target address to send the request to. * * @param url target address as a String * @return this HttpRequest * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); } return this; } /** * Get the request headers. * * @return headers to be sent */ public HttpHeaders getHeaders() { return headers; } /** * Set the request headers. * * @param headers the set of headers * @return this HttpRequest */ public HttpRequest setHeaders(HttpHeaders headers) { this.headers = headers; return this; } /** * Set a request header, replacing any existing value. A null for {@code value} will remove the header if one with * matching name exists. * * @param name the header name * @param value the header value * @return this HttpRequest */ public HttpRequest setHeader(String name, String value) { headers.set(name, value); return this; } /** * Get the request content. * * @return the content to be send */ public Flux<ByteBuffer> getBody() { return body == null ? null : body.toFluxByteBuffer(); } /** * Get the request content. * * @return the content to be send */ public BinaryData getBodyAsBinaryData() { return body; } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(String content) { this.body = BinaryData.fromString(content); setContentLength(this.body.getLength()); return this; } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ /** * Set request content. * <p> * Caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(Flux<ByteBuffer> content) { if (content != null) { setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(content))); } else { this.body = null; } return this; } /** * Set request content. * <p> * If provided content has known length, i.e. {@link BinaryData * Content-Length header is updated. Otherwise, * if provided content has unknown length, i.e. {@link BinaryData * the caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(BinaryData content) { this.body = content; if (content != null && content.getLength() != null) { setContentLength(content.getLength()); } return this; } private void setContentLength(long contentLength) { headers.set("Content-Length", String.valueOf(contentLength)); } /** * Creates a copy of the request. * * The main purpose of this is so that this HttpRequest can be changed and the resulting HttpRequest can be a * backup. This means that the cloned HttpHeaders and body must not be able to change from side effects of this * HttpRequest. * * @return a new HTTP request instance with cloned instances of all mutable properties. */ public HttpRequest copy() { final HttpHeaders bufferedHeaders = new HttpHeaders(headers); return new HttpRequest(httpMethod, url, bufferedHeaders, body); } }
class HttpRequest { private static final ClientLogger LOGGER = new ClientLogger(HttpRequest.class); private HttpMethod httpMethod; private URL url; private HttpHeaders headers; private BinaryData body; /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to */ public HttpRequest(HttpMethod httpMethod, URL url) { this(httpMethod, url, new HttpHeaders(), (BinaryData) null); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = httpMethod; setUrl(url); this.headers = new HttpHeaders(); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(body))); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, BinaryData body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(body); } /** * Get the request method. * * @return the request method */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Set the request method. * * @param httpMethod the request method * @return this HttpRequest */ public HttpRequest setHttpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } /** * Get the target address. * * @return the target address */ public URL getUrl() { return url; } /** * Set the target address to send the request to. * * @param url target address as {@link URL} * @return this HttpRequest */ public HttpRequest setUrl(URL url) { this.url = url; return this; } /** * Set the target address to send the request to. * * @param url target address as a String * @return this HttpRequest * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); } return this; } /** * Get the request headers. * * @return headers to be sent */ public HttpHeaders getHeaders() { return headers; } /** * Set the request headers. * * @param headers the set of headers * @return this HttpRequest */ public HttpRequest setHeaders(HttpHeaders headers) { this.headers = headers; return this; } /** * Set a request header, replacing any existing value. A null for {@code value} will remove the header if one with * matching name exists. * * @param name the header name * @param value the header value * @return this HttpRequest */ public HttpRequest setHeader(String name, String value) { headers.set(name, value); return this; } /** * Get the request content. * * @return the content to be sent */ public Flux<ByteBuffer> getBody() { return body == null ? null : body.toFluxByteBuffer(); } /** * Get the request content. * * @return the content to be sent */ public BinaryData getBodyAsBinaryData() { return body; } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(String content) { return setBody(BinaryData.fromString(content)); } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ /** * Set request content. * <p> * Caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(Flux<ByteBuffer> content) { if (content != null) { this.body = BinaryDataHelper.createBinaryData(new FluxByteBufferContent(content)); } else { this.body = null; } return this; } /** * Set request content. * <p> * If provided content has known length, i.e. {@link BinaryData * Content-Length header is updated. Otherwise, * if provided content has unknown length, i.e. {@link BinaryData * the caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(BinaryData content) { this.body = content; if (content != null && content.getLength() != null) { setContentLength(content.getLength()); } return this; } private void setContentLength(long contentLength) { headers.set("Content-Length", String.valueOf(contentLength)); } /** * Creates a copy of the request. * * The main purpose of this is so that this HttpRequest can be changed and the resulting HttpRequest can be a * backup. This means that the cloned HttpHeaders and body must not be able to change from side effects of this * HttpRequest. * * @return a new HTTP request instance with cloned instances of all mutable properties. */ public HttpRequest copy() { final HttpHeaders bufferedHeaders = new HttpHeaders(headers); return new HttpRequest(httpMethod, url, bufferedHeaders, body); } }
![image](https://user-images.githubusercontent.com/61715331/164538672-c8dde9e4-480a-4483-94eb-af050e728cc7.png)
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) { Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null."); return Mono.using(okio.Buffer::new, buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> { try { b.write(byteBuffer); return b; } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear) .switchIfEmpty(EMPTY_BYTE_STRING_MONO); }
.switchIfEmpty(EMPTY_BYTE_STRING_MONO);
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) { Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null."); return Mono.using(okio.Buffer::new, buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> { try { b.write(byteBuffer); return b; } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear) .switchIfEmpty(EMPTY_BYTE_STRING_MONO); }
class OkHttpAsyncHttpClient implements HttpClient { final OkHttpClient httpClient; private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY); OkHttpAsyncHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Mono<HttpResponse> send(HttpRequest request) { return send(request, Context.NONE); } @Override public Mono<HttpResponse> send(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false); return Mono.create(sink -> sink.onRequest(value -> { toOkHttpRequest(request).subscribe(okHttpRequest -> { try { Call call = httpClient.newCall(okHttpRequest); call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse)); sink.onCancel(call::cancel); } catch (Exception ex) { sink.error(ex); } }, sink::error); })); } /** * Converts the given azure-core request to okhttp request. * * @param request the azure-core request * @return the Mono emitting okhttp request */ private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (HttpHeader hdr : request.getHeaders()) { hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return Mono.just(requestBuilder.get().build()); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return Mono.just(requestBuilder.head().build()); } return toOkHttpRequestBody(request.getBody(), request.getHeaders()) .map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody) .build()); } /** * Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux. * * @param bbFlux stream of java.nio.ByteBuffer representing request content * @param headers the headers associated with the original request * @return the Mono emitting okhttp3.RequestBody */ private static Mono<RequestBody> toOkHttpRequestBody(Flux<ByteBuffer> bbFlux, HttpHeaders headers) { Mono<okio.ByteString> bsMono = bbFlux == null ? EMPTY_BYTE_STRING_MONO : toByteString(bbFlux); return bsMono.map(bs -> { String contentType = headers.getValue("Content-Type"); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); return RequestBody.create(bs, mediaType); }); } /** * Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString. * * Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be * written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get * copied to one single byte array and okio.ByteString will be created referring this byte array. Finally the * initial okio.Buffer will be returned to the pool. * * @param bbFlux the Flux of ByteBuffer to aggregate * @return a mono emitting aggregated ByteString */ private static class OkHttpCallback implements okhttp3.Callback { private final MonoSink<HttpResponse> sink; private final HttpRequest request; private final boolean eagerlyReadResponse; OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) { this.sink = sink; this.request = request; this.eagerlyReadResponse = eagerlyReadResponse; } @SuppressWarnings("NullableProblems") @Override public void onFailure(okhttp3.Call call, IOException e) { sink.error(e); } @SuppressWarnings("NullableProblems") @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) { /* * Use a buffered response when we are eagerly reading the response from the network and the body isn't * empty. */ if (eagerlyReadResponse) { ResponseBody body = response.body(); if (Objects.nonNull(body)) { try { byte[] bytes = body.bytes(); body.close(); sink.success(new OkHttpAsyncBufferedResponse(response, request, bytes)); } catch (IOException ex) { sink.error(ex); } } else { sink.success(new OkHttpAsyncResponse(response, request)); } } else { sink.success(new OkHttpAsyncResponse(response, request)); } } } }
class OkHttpAsyncHttpClient implements HttpClient { final OkHttpClient httpClient; private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY); OkHttpAsyncHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Mono<HttpResponse> send(HttpRequest request) { return send(request, Context.NONE); } @Override public Mono<HttpResponse> send(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false); return Mono.create(sink -> sink.onRequest(value -> { toOkHttpRequest(request).subscribe(okHttpRequest -> { try { Call call = httpClient.newCall(okHttpRequest); call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse)); sink.onCancel(call::cancel); } catch (Exception ex) { sink.error(ex); } }, sink::error); })); } /** * Converts the given azure-core request to okhttp request. * * @param request the azure-core request * @return the Mono emitting okhttp request */ private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (HttpHeader hdr : request.getHeaders()) { hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return Mono.just(requestBuilder.get().build()); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return Mono.just(requestBuilder.head().build()); } return toOkHttpRequestBody(request.getBody(), request.getHeaders()) .map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody) .build()); } /** * Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux. * * @param bbFlux stream of java.nio.ByteBuffer representing request content * @param headers the headers associated with the original request * @return the Mono emitting okhttp3.RequestBody */ private static Mono<RequestBody> toOkHttpRequestBody(Flux<ByteBuffer> bbFlux, HttpHeaders headers) { Mono<okio.ByteString> bsMono = bbFlux == null ? EMPTY_BYTE_STRING_MONO : toByteString(bbFlux); return bsMono.map(bs -> { String contentType = headers.getValue("Content-Type"); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); return RequestBody.create(bs, mediaType); }); } /** * Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString. * * Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be * written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get * copied to one single byte array and okio.ByteString will be created referring this byte array. Finally the * initial okio.Buffer will be returned to the pool. * * @param bbFlux the Flux of ByteBuffer to aggregate * @return a mono emitting aggregated ByteString */ private static class OkHttpCallback implements okhttp3.Callback { private final MonoSink<HttpResponse> sink; private final HttpRequest request; private final boolean eagerlyReadResponse; OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) { this.sink = sink; this.request = request; this.eagerlyReadResponse = eagerlyReadResponse; } @SuppressWarnings("NullableProblems") @Override public void onFailure(okhttp3.Call call, IOException e) { sink.error(e); } @SuppressWarnings("NullableProblems") @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) { /* * Use a buffered response when we are eagerly reading the response from the network and the body isn't * empty. */ if (eagerlyReadResponse) { ResponseBody body = response.body(); if (Objects.nonNull(body)) { try { byte[] bytes = body.bytes(); body.close(); sink.success(new OkHttpAsyncBufferedResponse(response, request, bytes)); } catch (IOException ex) { sink.error(ex); } } else { sink.success(new OkHttpAsyncResponse(response, request)); } } else { sink.success(new OkHttpAsyncResponse(response, request)); } } } }
Is it same? (system env vs. local property map)
void testAllowedHeadersFromSystemProperties() { Properties properties = new Properties(); properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); }
properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade");
void testAllowedHeadersFromSystemProperties() { Properties properties = new Properties(); properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); }
class JdkAsyncHttpClientBuilderTests { private static final String PROXY_USERNAME = "foo"; private static final String PROXY_PASSWORD = "bar"; private static final String PROXY_USER_INFO = PROXY_USERNAME + ":" + PROXY_PASSWORD + "@"; private static final String SERVICE_ENDPOINT = "/default"; private static final ConfigurationSource EMPTY_SOURCE = new TestConfigurationSource(); /** * Tests that an {@link JdkAsyncHttpClient} is able to be built from an existing * {@link java.net.http.HttpClient.Builder}. */ @Test public void buildClientWithExistingClient() { final String[] marker = new String[1]; final java.net.http.HttpClient.Builder existingClientBuilder = java.net.http.HttpClient.newBuilder(); existingClientBuilder.executor(new Executor() { private final ExecutorService executorService = Executors.newFixedThreadPool(2); @Override public void execute(Runnable command) { marker[0] = "on_custom_executor"; executorService.submit(command); } }); final JdkAsyncHttpClient client = (JdkAsyncHttpClient) new JdkAsyncHttpClientBuilder(existingClientBuilder) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(client.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } assertNotNull(marker[0]); assertEquals(marker[0], "on_custom_executor"); } /** * Tests that instantiating an {@link JdkAsyncHttpClientBuilder} with a {@code null} {@link JdkAsyncHttpClient} * will throw a {@link NullPointerException}. */ @Test public void startingWithNullClientThrows() { assertThrows(NullPointerException.class, () -> new JdkAsyncHttpClientBuilder(null)); } /** * Tests building a client with a given {@code Executor}. */ @Test public void buildWithExecutor() { final String[] marker = new String[1]; final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .executor(new Executor() { private final ExecutorService executorService = Executors.newFixedThreadPool(10); @Override public void execute(Runnable command) { marker[0] = "on_custom_executor"; executorService.submit(command); } }) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } assertNotNull(marker[0]); assertEquals(marker[0], "on_custom_executor"); } /** * Tests that passing a {@code null} {@code executor} to the builder will throw a * {@link NullPointerException}. */ @Test public void nullExecutorThrows() { assertThrows(NullPointerException.class, () -> new JdkAsyncHttpClientBuilder().executor(null)); } /** * Tests building a client with a given proxy. */ @Test public void buildWithHttpProxy() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); ProxyOptions clientProxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())) .setCredentials(PROXY_USERNAME, PROXY_PASSWORD); HttpClient httpClient = new JdkAsyncHttpClientBuilder(java.net.http.HttpClient.newBuilder()) .proxy(clientProxyOptions) .build(); final String serviceUrl = "http: StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, serviceUrl))) .expectNextCount(1) .verifyComplete(); } finally { proxyServer.shutdown(); } } @Test public void buildWithHttpProxyFromEnvConfiguration() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); Configuration configuration = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, new TestConfigurationSource() .put(Configuration.PROPERTY_HTTP_PROXY, "http: .put("java.net.useSystemProxies", "true")) .build(); configurationProxyTest(configuration); } finally { proxyServer.shutdown(); } } @Test public void buildWithHttpProxyFromExplicitConfiguration() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); Configuration configuration = new ConfigurationBuilder() .putProperty("http.proxy.hostname", proxyEndpoint.getHost()) .putProperty("http.proxy.port", String.valueOf(proxyEndpoint.getPort())) .build(); configurationProxyTest(configuration); } finally { proxyServer.shutdown(); } } @Test public void buildWithConfigurationNone() { final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .configuration(Configuration.NONE) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } } @ParameterizedTest @MethodSource("buildWithExplicitConfigurationProxySupplier") public void buildWithNonProxyConfigurationProxy(Configuration configuration) { final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .configuration(configuration) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } } private static Stream<Arguments> buildWithExplicitConfigurationProxySupplier() { List<Arguments> arguments = new ArrayList<>(); final Configuration envConfiguration = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, new TestConfigurationSource() .put(Configuration.PROPERTY_HTTP_PROXY, "http: .put(Configuration.PROPERTY_NO_PROXY, "localhost")) .build(); arguments.add(Arguments.of(envConfiguration)); final Configuration explicitConfiguration = new ConfigurationBuilder() .putProperty("http.proxy.hostname", "localhost") .putProperty("http.proxy.port", "42") .putProperty("http.proxy.non-proxy-hosts", "localhost") .build(); arguments.add(Arguments.of(explicitConfiguration)); return arguments.stream(); } @Test void testAllowedHeadersFromNetworkProperties() { JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); Properties properties = new Properties(); properties.put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); } @Test void testAllowedHeadersFromConfiguration() { Configuration configuration = new ConfigurationBuilder(EMPTY_SOURCE, new TestConfigurationSource().put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"), EMPTY_SOURCE) .build(); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy( new JdkAsyncHttpClientBuilder().configuration(configuration)); Properties properties = new Properties(); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); } @Test void testAllowedHeadersFromBoth() { Configuration configuration = new ConfigurationBuilder(new TestConfigurationSource(), new TestConfigurationSource().put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"), new TestConfigurationSource()) .build(); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy( new JdkAsyncHttpClientBuilder().configuration(configuration)); Properties properties = new Properties(); properties.put("jdk.httpclient.allowRestrictedHeaders", "host, connection, upgrade"); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "host", "connection", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 1); } @Test @Test void testCaseInsensitivity() { Properties properties = new Properties(); properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-LENGTH"); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> restrictedHeaders = jdkAsyncHttpClientBuilder.getRestrictedHeaders(); assertTrue(restrictedHeaders.contains("Connection"), "connection header is missing"); assertTrue(restrictedHeaders.contains("connection"), "connection header is missing"); assertTrue(restrictedHeaders.contains("CONNECTION"), "connection header is missing"); assertFalse(restrictedHeaders.contains("Content-Length"), "content-length not removed"); assertFalse(restrictedHeaders.contains("content-length"), "content-length not removed"); assertFalse(restrictedHeaders.contains("CONTENT-length"), "content-length not removed"); } private static void configurationProxyTest(Configuration configuration) { HttpClient httpClient = new JdkAsyncHttpClientBuilder(java.net.http.HttpClient.newBuilder()) .configuration(configuration) .build(); final String serviceUrl = "http: StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, serviceUrl))) .expectNextCount(1) .verifyComplete(); } private void validateRestrictedHeaders(JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder, Set<String> expectedRestrictedHeaders, int expectedRestrictedHeadersSize) { Set<String> restrictedHeaders = jdkAsyncHttpClientBuilder.getRestrictedHeaders(); assertEquals(expectedRestrictedHeadersSize, restrictedHeaders.size()); assertEquals(expectedRestrictedHeaders, restrictedHeaders); } }
class JdkAsyncHttpClientBuilderTests { private static final String PROXY_USERNAME = "foo"; private static final String PROXY_PASSWORD = "bar"; private static final String PROXY_USER_INFO = PROXY_USERNAME + ":" + PROXY_PASSWORD + "@"; private static final String SERVICE_ENDPOINT = "/default"; private static final ConfigurationSource EMPTY_SOURCE = new TestConfigurationSource(); /** * Tests that an {@link JdkAsyncHttpClient} is able to be built from an existing * {@link java.net.http.HttpClient.Builder}. */ @Test public void buildClientWithExistingClient() { final String[] marker = new String[1]; final java.net.http.HttpClient.Builder existingClientBuilder = java.net.http.HttpClient.newBuilder(); existingClientBuilder.executor(new Executor() { private final ExecutorService executorService = Executors.newFixedThreadPool(2); @Override public void execute(Runnable command) { marker[0] = "on_custom_executor"; executorService.submit(command); } }); final JdkAsyncHttpClient client = (JdkAsyncHttpClient) new JdkAsyncHttpClientBuilder(existingClientBuilder) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(client.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } assertNotNull(marker[0]); assertEquals(marker[0], "on_custom_executor"); } /** * Tests that instantiating an {@link JdkAsyncHttpClientBuilder} with a {@code null} {@link JdkAsyncHttpClient} * will throw a {@link NullPointerException}. */ @Test public void startingWithNullClientThrows() { assertThrows(NullPointerException.class, () -> new JdkAsyncHttpClientBuilder(null)); } /** * Tests building a client with a given {@code Executor}. */ @Test public void buildWithExecutor() { final String[] marker = new String[1]; final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .executor(new Executor() { private final ExecutorService executorService = Executors.newFixedThreadPool(10); @Override public void execute(Runnable command) { marker[0] = "on_custom_executor"; executorService.submit(command); } }) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } assertNotNull(marker[0]); assertEquals(marker[0], "on_custom_executor"); } /** * Tests that passing a {@code null} {@code executor} to the builder will throw a * {@link NullPointerException}. */ @Test public void nullExecutorThrows() { assertThrows(NullPointerException.class, () -> new JdkAsyncHttpClientBuilder().executor(null)); } /** * Tests building a client with a given proxy. */ @Test public void buildWithHttpProxy() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); ProxyOptions clientProxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())) .setCredentials(PROXY_USERNAME, PROXY_PASSWORD); HttpClient httpClient = new JdkAsyncHttpClientBuilder(java.net.http.HttpClient.newBuilder()) .proxy(clientProxyOptions) .build(); final String serviceUrl = "http: StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, serviceUrl))) .expectNextCount(1) .verifyComplete(); } finally { proxyServer.shutdown(); } } @Test public void buildWithHttpProxyFromEnvConfiguration() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); Configuration configuration = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, new TestConfigurationSource() .put(Configuration.PROPERTY_HTTP_PROXY, "http: .put("java.net.useSystemProxies", "true")) .build(); configurationProxyTest(configuration); } finally { proxyServer.shutdown(); } } @Test public void buildWithHttpProxyFromExplicitConfiguration() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); Configuration configuration = new ConfigurationBuilder() .putProperty("http.proxy.hostname", proxyEndpoint.getHost()) .putProperty("http.proxy.port", String.valueOf(proxyEndpoint.getPort())) .build(); configurationProxyTest(configuration); } finally { proxyServer.shutdown(); } } @Test public void buildWithConfigurationNone() { final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .configuration(Configuration.NONE) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } } @ParameterizedTest @MethodSource("buildWithExplicitConfigurationProxySupplier") public void buildWithNonProxyConfigurationProxy(Configuration configuration) { final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .configuration(configuration) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } } private static Stream<Arguments> buildWithExplicitConfigurationProxySupplier() { List<Arguments> arguments = new ArrayList<>(); final Configuration envConfiguration = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, new TestConfigurationSource() .put(Configuration.PROPERTY_HTTP_PROXY, "http: .put(Configuration.PROPERTY_NO_PROXY, "localhost")) .build(); arguments.add(Arguments.of(envConfiguration)); final Configuration explicitConfiguration = new ConfigurationBuilder() .putProperty("http.proxy.hostname", "localhost") .putProperty("http.proxy.port", "42") .putProperty("http.proxy.non-proxy-hosts", "localhost") .build(); arguments.add(Arguments.of(explicitConfiguration)); return arguments.stream(); } @Test void testAllowedHeadersFromNetworkProperties() { JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); Properties properties = new Properties(); properties.put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); } @Test void testAllowedHeadersFromConfiguration() { Configuration configuration = new ConfigurationBuilder(EMPTY_SOURCE, new TestConfigurationSource().put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"), EMPTY_SOURCE) .build(); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy( new JdkAsyncHttpClientBuilder().configuration(configuration)); Properties properties = new Properties(); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); } @Test void testAllowedHeadersFromBoth() { Configuration configuration = new ConfigurationBuilder(new TestConfigurationSource(), new TestConfigurationSource().put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"), new TestConfigurationSource()) .build(); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy( new JdkAsyncHttpClientBuilder().configuration(configuration)); Properties properties = new Properties(); properties.put("jdk.httpclient.allowRestrictedHeaders", "host, connection, upgrade"); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "host", "connection", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 1); } @Test @Test void testCaseInsensitivity() { Properties properties = new Properties(); properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-LENGTH"); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> restrictedHeaders = jdkAsyncHttpClientBuilder.getRestrictedHeaders(); assertTrue(restrictedHeaders.contains("Connection"), "connection header is missing"); assertTrue(restrictedHeaders.contains("connection"), "connection header is missing"); assertTrue(restrictedHeaders.contains("CONNECTION"), "connection header is missing"); assertFalse(restrictedHeaders.contains("Content-Length"), "content-length not removed"); assertFalse(restrictedHeaders.contains("content-length"), "content-length not removed"); assertFalse(restrictedHeaders.contains("CONTENT-length"), "content-length not removed"); } private static void configurationProxyTest(Configuration configuration) { HttpClient httpClient = new JdkAsyncHttpClientBuilder(java.net.http.HttpClient.newBuilder()) .configuration(configuration) .build(); final String serviceUrl = "http: StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, serviceUrl))) .expectNextCount(1) .verifyComplete(); } private void validateRestrictedHeaders(JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder, Set<String> expectedRestrictedHeaders, int expectedRestrictedHeadersSize) { Set<String> restrictedHeaders = jdkAsyncHttpClientBuilder.getRestrictedHeaders(); assertEquals(expectedRestrictedHeadersSize, restrictedHeaders.size()); assertEquals(expectedRestrictedHeaders, restrictedHeaders); } }
Yes, this will perform the same testing as `new Properties()` looked up values in the System properties. This just localizes the test to be thread-safe as it no longer mutates global state
void testAllowedHeadersFromSystemProperties() { Properties properties = new Properties(); properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); }
properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade");
void testAllowedHeadersFromSystemProperties() { Properties properties = new Properties(); properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); }
class JdkAsyncHttpClientBuilderTests { private static final String PROXY_USERNAME = "foo"; private static final String PROXY_PASSWORD = "bar"; private static final String PROXY_USER_INFO = PROXY_USERNAME + ":" + PROXY_PASSWORD + "@"; private static final String SERVICE_ENDPOINT = "/default"; private static final ConfigurationSource EMPTY_SOURCE = new TestConfigurationSource(); /** * Tests that an {@link JdkAsyncHttpClient} is able to be built from an existing * {@link java.net.http.HttpClient.Builder}. */ @Test public void buildClientWithExistingClient() { final String[] marker = new String[1]; final java.net.http.HttpClient.Builder existingClientBuilder = java.net.http.HttpClient.newBuilder(); existingClientBuilder.executor(new Executor() { private final ExecutorService executorService = Executors.newFixedThreadPool(2); @Override public void execute(Runnable command) { marker[0] = "on_custom_executor"; executorService.submit(command); } }); final JdkAsyncHttpClient client = (JdkAsyncHttpClient) new JdkAsyncHttpClientBuilder(existingClientBuilder) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(client.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } assertNotNull(marker[0]); assertEquals(marker[0], "on_custom_executor"); } /** * Tests that instantiating an {@link JdkAsyncHttpClientBuilder} with a {@code null} {@link JdkAsyncHttpClient} * will throw a {@link NullPointerException}. */ @Test public void startingWithNullClientThrows() { assertThrows(NullPointerException.class, () -> new JdkAsyncHttpClientBuilder(null)); } /** * Tests building a client with a given {@code Executor}. */ @Test public void buildWithExecutor() { final String[] marker = new String[1]; final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .executor(new Executor() { private final ExecutorService executorService = Executors.newFixedThreadPool(10); @Override public void execute(Runnable command) { marker[0] = "on_custom_executor"; executorService.submit(command); } }) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } assertNotNull(marker[0]); assertEquals(marker[0], "on_custom_executor"); } /** * Tests that passing a {@code null} {@code executor} to the builder will throw a * {@link NullPointerException}. */ @Test public void nullExecutorThrows() { assertThrows(NullPointerException.class, () -> new JdkAsyncHttpClientBuilder().executor(null)); } /** * Tests building a client with a given proxy. */ @Test public void buildWithHttpProxy() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); ProxyOptions clientProxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())) .setCredentials(PROXY_USERNAME, PROXY_PASSWORD); HttpClient httpClient = new JdkAsyncHttpClientBuilder(java.net.http.HttpClient.newBuilder()) .proxy(clientProxyOptions) .build(); final String serviceUrl = "http: StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, serviceUrl))) .expectNextCount(1) .verifyComplete(); } finally { proxyServer.shutdown(); } } @Test public void buildWithHttpProxyFromEnvConfiguration() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); Configuration configuration = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, new TestConfigurationSource() .put(Configuration.PROPERTY_HTTP_PROXY, "http: .put("java.net.useSystemProxies", "true")) .build(); configurationProxyTest(configuration); } finally { proxyServer.shutdown(); } } @Test public void buildWithHttpProxyFromExplicitConfiguration() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); Configuration configuration = new ConfigurationBuilder() .putProperty("http.proxy.hostname", proxyEndpoint.getHost()) .putProperty("http.proxy.port", String.valueOf(proxyEndpoint.getPort())) .build(); configurationProxyTest(configuration); } finally { proxyServer.shutdown(); } } @Test public void buildWithConfigurationNone() { final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .configuration(Configuration.NONE) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } } @ParameterizedTest @MethodSource("buildWithExplicitConfigurationProxySupplier") public void buildWithNonProxyConfigurationProxy(Configuration configuration) { final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .configuration(configuration) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } } private static Stream<Arguments> buildWithExplicitConfigurationProxySupplier() { List<Arguments> arguments = new ArrayList<>(); final Configuration envConfiguration = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, new TestConfigurationSource() .put(Configuration.PROPERTY_HTTP_PROXY, "http: .put(Configuration.PROPERTY_NO_PROXY, "localhost")) .build(); arguments.add(Arguments.of(envConfiguration)); final Configuration explicitConfiguration = new ConfigurationBuilder() .putProperty("http.proxy.hostname", "localhost") .putProperty("http.proxy.port", "42") .putProperty("http.proxy.non-proxy-hosts", "localhost") .build(); arguments.add(Arguments.of(explicitConfiguration)); return arguments.stream(); } @Test void testAllowedHeadersFromNetworkProperties() { JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); Properties properties = new Properties(); properties.put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); } @Test void testAllowedHeadersFromConfiguration() { Configuration configuration = new ConfigurationBuilder(EMPTY_SOURCE, new TestConfigurationSource().put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"), EMPTY_SOURCE) .build(); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy( new JdkAsyncHttpClientBuilder().configuration(configuration)); Properties properties = new Properties(); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); } @Test void testAllowedHeadersFromBoth() { Configuration configuration = new ConfigurationBuilder(new TestConfigurationSource(), new TestConfigurationSource().put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"), new TestConfigurationSource()) .build(); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy( new JdkAsyncHttpClientBuilder().configuration(configuration)); Properties properties = new Properties(); properties.put("jdk.httpclient.allowRestrictedHeaders", "host, connection, upgrade"); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "host", "connection", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 1); } @Test @Test void testCaseInsensitivity() { Properties properties = new Properties(); properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-LENGTH"); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> restrictedHeaders = jdkAsyncHttpClientBuilder.getRestrictedHeaders(); assertTrue(restrictedHeaders.contains("Connection"), "connection header is missing"); assertTrue(restrictedHeaders.contains("connection"), "connection header is missing"); assertTrue(restrictedHeaders.contains("CONNECTION"), "connection header is missing"); assertFalse(restrictedHeaders.contains("Content-Length"), "content-length not removed"); assertFalse(restrictedHeaders.contains("content-length"), "content-length not removed"); assertFalse(restrictedHeaders.contains("CONTENT-length"), "content-length not removed"); } private static void configurationProxyTest(Configuration configuration) { HttpClient httpClient = new JdkAsyncHttpClientBuilder(java.net.http.HttpClient.newBuilder()) .configuration(configuration) .build(); final String serviceUrl = "http: StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, serviceUrl))) .expectNextCount(1) .verifyComplete(); } private void validateRestrictedHeaders(JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder, Set<String> expectedRestrictedHeaders, int expectedRestrictedHeadersSize) { Set<String> restrictedHeaders = jdkAsyncHttpClientBuilder.getRestrictedHeaders(); assertEquals(expectedRestrictedHeadersSize, restrictedHeaders.size()); assertEquals(expectedRestrictedHeaders, restrictedHeaders); } }
class JdkAsyncHttpClientBuilderTests { private static final String PROXY_USERNAME = "foo"; private static final String PROXY_PASSWORD = "bar"; private static final String PROXY_USER_INFO = PROXY_USERNAME + ":" + PROXY_PASSWORD + "@"; private static final String SERVICE_ENDPOINT = "/default"; private static final ConfigurationSource EMPTY_SOURCE = new TestConfigurationSource(); /** * Tests that an {@link JdkAsyncHttpClient} is able to be built from an existing * {@link java.net.http.HttpClient.Builder}. */ @Test public void buildClientWithExistingClient() { final String[] marker = new String[1]; final java.net.http.HttpClient.Builder existingClientBuilder = java.net.http.HttpClient.newBuilder(); existingClientBuilder.executor(new Executor() { private final ExecutorService executorService = Executors.newFixedThreadPool(2); @Override public void execute(Runnable command) { marker[0] = "on_custom_executor"; executorService.submit(command); } }); final JdkAsyncHttpClient client = (JdkAsyncHttpClient) new JdkAsyncHttpClientBuilder(existingClientBuilder) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(client.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } assertNotNull(marker[0]); assertEquals(marker[0], "on_custom_executor"); } /** * Tests that instantiating an {@link JdkAsyncHttpClientBuilder} with a {@code null} {@link JdkAsyncHttpClient} * will throw a {@link NullPointerException}. */ @Test public void startingWithNullClientThrows() { assertThrows(NullPointerException.class, () -> new JdkAsyncHttpClientBuilder(null)); } /** * Tests building a client with a given {@code Executor}. */ @Test public void buildWithExecutor() { final String[] marker = new String[1]; final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .executor(new Executor() { private final ExecutorService executorService = Executors.newFixedThreadPool(10); @Override public void execute(Runnable command) { marker[0] = "on_custom_executor"; executorService.submit(command); } }) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } assertNotNull(marker[0]); assertEquals(marker[0], "on_custom_executor"); } /** * Tests that passing a {@code null} {@code executor} to the builder will throw a * {@link NullPointerException}. */ @Test public void nullExecutorThrows() { assertThrows(NullPointerException.class, () -> new JdkAsyncHttpClientBuilder().executor(null)); } /** * Tests building a client with a given proxy. */ @Test public void buildWithHttpProxy() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); ProxyOptions clientProxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())) .setCredentials(PROXY_USERNAME, PROXY_PASSWORD); HttpClient httpClient = new JdkAsyncHttpClientBuilder(java.net.http.HttpClient.newBuilder()) .proxy(clientProxyOptions) .build(); final String serviceUrl = "http: StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, serviceUrl))) .expectNextCount(1) .verifyComplete(); } finally { proxyServer.shutdown(); } } @Test public void buildWithHttpProxyFromEnvConfiguration() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); Configuration configuration = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, new TestConfigurationSource() .put(Configuration.PROPERTY_HTTP_PROXY, "http: .put("java.net.useSystemProxies", "true")) .build(); configurationProxyTest(configuration); } finally { proxyServer.shutdown(); } } @Test public void buildWithHttpProxyFromExplicitConfiguration() { final SimpleBasicAuthHttpProxyServer proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, new String[] {SERVICE_ENDPOINT}); try { SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint = proxyServer.start(); Configuration configuration = new ConfigurationBuilder() .putProperty("http.proxy.hostname", proxyEndpoint.getHost()) .putProperty("http.proxy.port", String.valueOf(proxyEndpoint.getPort())) .build(); configurationProxyTest(configuration); } finally { proxyServer.shutdown(); } } @Test public void buildWithConfigurationNone() { final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .configuration(Configuration.NONE) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } } @ParameterizedTest @MethodSource("buildWithExplicitConfigurationProxySupplier") public void buildWithNonProxyConfigurationProxy(Configuration configuration) { final HttpClient httpClient = new JdkAsyncHttpClientBuilder() .configuration(configuration) .build(); final String defaultPath = "/default"; final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort().disableRequestJournal()); server.stubFor(WireMock.get(defaultPath).willReturn(WireMock.aResponse().withStatus(200))); server.start(); final String defaultUrl = "http: try { StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, defaultUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } finally { if (server.isRunning()) { server.shutdown(); } } } private static Stream<Arguments> buildWithExplicitConfigurationProxySupplier() { List<Arguments> arguments = new ArrayList<>(); final Configuration envConfiguration = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, new TestConfigurationSource() .put(Configuration.PROPERTY_HTTP_PROXY, "http: .put(Configuration.PROPERTY_NO_PROXY, "localhost")) .build(); arguments.add(Arguments.of(envConfiguration)); final Configuration explicitConfiguration = new ConfigurationBuilder() .putProperty("http.proxy.hostname", "localhost") .putProperty("http.proxy.port", "42") .putProperty("http.proxy.non-proxy-hosts", "localhost") .build(); arguments.add(Arguments.of(explicitConfiguration)); return arguments.stream(); } @Test void testAllowedHeadersFromNetworkProperties() { JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); Properties properties = new Properties(); properties.put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); } @Test void testAllowedHeadersFromConfiguration() { Configuration configuration = new ConfigurationBuilder(EMPTY_SOURCE, new TestConfigurationSource().put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"), EMPTY_SOURCE) .build(); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy( new JdkAsyncHttpClientBuilder().configuration(configuration)); Properties properties = new Properties(); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 3); } @Test void testAllowedHeadersFromBoth() { Configuration configuration = new ConfigurationBuilder(new TestConfigurationSource(), new TestConfigurationSource().put("jdk.httpclient.allowRestrictedHeaders", "content-length, upgrade"), new TestConfigurationSource()) .build(); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy( new JdkAsyncHttpClientBuilder().configuration(configuration)); Properties properties = new Properties(); properties.put("jdk.httpclient.allowRestrictedHeaders", "host, connection, upgrade"); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> expectedRestrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); expectedRestrictedHeaders.addAll(JdkAsyncHttpClientBuilder.DEFAULT_RESTRICTED_HEADERS); expectedRestrictedHeaders.removeAll(Arrays.asList("content-length", "host", "connection", "upgrade")); validateRestrictedHeaders(jdkAsyncHttpClientBuilder, expectedRestrictedHeaders, 1); } @Test @Test void testCaseInsensitivity() { Properties properties = new Properties(); properties.setProperty("jdk.httpclient.allowRestrictedHeaders", "content-LENGTH"); JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder = spy(new JdkAsyncHttpClientBuilder()); when(jdkAsyncHttpClientBuilder.getNetworkProperties()).thenReturn(properties); Set<String> restrictedHeaders = jdkAsyncHttpClientBuilder.getRestrictedHeaders(); assertTrue(restrictedHeaders.contains("Connection"), "connection header is missing"); assertTrue(restrictedHeaders.contains("connection"), "connection header is missing"); assertTrue(restrictedHeaders.contains("CONNECTION"), "connection header is missing"); assertFalse(restrictedHeaders.contains("Content-Length"), "content-length not removed"); assertFalse(restrictedHeaders.contains("content-length"), "content-length not removed"); assertFalse(restrictedHeaders.contains("CONTENT-length"), "content-length not removed"); } private static void configurationProxyTest(Configuration configuration) { HttpClient httpClient = new JdkAsyncHttpClientBuilder(java.net.http.HttpClient.newBuilder()) .configuration(configuration) .build(); final String serviceUrl = "http: StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, serviceUrl))) .expectNextCount(1) .verifyComplete(); } private void validateRestrictedHeaders(JdkAsyncHttpClientBuilder jdkAsyncHttpClientBuilder, Set<String> expectedRestrictedHeaders, int expectedRestrictedHeadersSize) { Set<String> restrictedHeaders = jdkAsyncHttpClientBuilder.getRestrictedHeaders(); assertEquals(expectedRestrictedHeadersSize, restrictedHeaders.size()); assertEquals(expectedRestrictedHeaders, restrictedHeaders); } }
Opposite comment from the above, this doesn't seem to need to call into `setBody(BinaryData)` as it won't set the Content-Length (unless `FluxByteBufferContent` is eagerly reading the `Flux<ByteBuffer>`).
public HttpRequest setBody(Flux<ByteBuffer> content) { if (content != null) { setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(content))); } else { this.body = null; } return this; }
setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(content)));
public HttpRequest setBody(Flux<ByteBuffer> content) { if (content != null) { this.body = BinaryDataHelper.createBinaryData(new FluxByteBufferContent(content)); } else { this.body = null; } return this; }
class HttpRequest { private static final ClientLogger LOGGER = new ClientLogger(HttpRequest.class); private HttpMethod httpMethod; private URL url; private HttpHeaders headers; private BinaryData body; /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to */ public HttpRequest(HttpMethod httpMethod, URL url) { this(httpMethod, url, new HttpHeaders(), (BinaryData) null); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = httpMethod; setUrl(url); this.headers = new HttpHeaders(); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(body))); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, BinaryData body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(body); } /** * Get the request method. * * @return the request method */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Set the request method. * * @param httpMethod the request method * @return this HttpRequest */ public HttpRequest setHttpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } /** * Get the target address. * * @return the target address */ public URL getUrl() { return url; } /** * Set the target address to send the request to. * * @param url target address as {@link URL} * @return this HttpRequest */ public HttpRequest setUrl(URL url) { this.url = url; return this; } /** * Set the target address to send the request to. * * @param url target address as a String * @return this HttpRequest * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); } return this; } /** * Get the request headers. * * @return headers to be sent */ public HttpHeaders getHeaders() { return headers; } /** * Set the request headers. * * @param headers the set of headers * @return this HttpRequest */ public HttpRequest setHeaders(HttpHeaders headers) { this.headers = headers; return this; } /** * Set a request header, replacing any existing value. A null for {@code value} will remove the header if one with * matching name exists. * * @param name the header name * @param value the header value * @return this HttpRequest */ public HttpRequest setHeader(String name, String value) { headers.set(name, value); return this; } /** * Get the request content. * * @return the content to be send */ public Flux<ByteBuffer> getBody() { return body == null ? null : body.toFluxByteBuffer(); } /** * Get the request content. * * @return the content to be send */ public BinaryData getBodyAsBinaryData() { return body; } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(String content) { this.body = BinaryData.fromString(content); setContentLength(this.body.getLength()); return this; } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(byte[] content) { setContentLength(content.length); this.body = BinaryData.fromBytes(content); return this; } /** * Set request content. * <p> * Caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ /** * Set request content. * <p> * If provided content has known length, i.e. {@link BinaryData * Content-Length header is updated. Otherwise, * if provided content has unknown length, i.e. {@link BinaryData * the caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(BinaryData content) { this.body = content; if (content != null && content.getLength() != null) { setContentLength(content.getLength()); } return this; } private void setContentLength(long contentLength) { headers.set("Content-Length", String.valueOf(contentLength)); } /** * Creates a copy of the request. * * The main purpose of this is so that this HttpRequest can be changed and the resulting HttpRequest can be a * backup. This means that the cloned HttpHeaders and body must not be able to change from side effects of this * HttpRequest. * * @return a new HTTP request instance with cloned instances of all mutable properties. */ public HttpRequest copy() { final HttpHeaders bufferedHeaders = new HttpHeaders(headers); return new HttpRequest(httpMethod, url, bufferedHeaders, body); } }
class HttpRequest { private static final ClientLogger LOGGER = new ClientLogger(HttpRequest.class); private HttpMethod httpMethod; private URL url; private HttpHeaders headers; private BinaryData body; /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to */ public HttpRequest(HttpMethod httpMethod, URL url) { this(httpMethod, url, new HttpHeaders(), (BinaryData) null); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = httpMethod; setUrl(url); this.headers = new HttpHeaders(); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(BinaryDataHelper.createBinaryData(new FluxByteBufferContent(body))); } /** * Create a new HttpRequest instance. * * @param httpMethod the HTTP request method * @param url the target address to send the request to * @param headers the HTTP headers to use with this request * @param body the request content */ public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, BinaryData body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; setBody(body); } /** * Get the request method. * * @return the request method */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Set the request method. * * @param httpMethod the request method * @return this HttpRequest */ public HttpRequest setHttpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } /** * Get the target address. * * @return the target address */ public URL getUrl() { return url; } /** * Set the target address to send the request to. * * @param url target address as {@link URL} * @return this HttpRequest */ public HttpRequest setUrl(URL url) { this.url = url; return this; } /** * Set the target address to send the request to. * * @param url target address as a String * @return this HttpRequest * @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL. */ public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); } return this; } /** * Get the request headers. * * @return headers to be sent */ public HttpHeaders getHeaders() { return headers; } /** * Set the request headers. * * @param headers the set of headers * @return this HttpRequest */ public HttpRequest setHeaders(HttpHeaders headers) { this.headers = headers; return this; } /** * Set a request header, replacing any existing value. A null for {@code value} will remove the header if one with * matching name exists. * * @param name the header name * @param value the header value * @return this HttpRequest */ public HttpRequest setHeader(String name, String value) { headers.set(name, value); return this; } /** * Get the request content. * * @return the content to be sent */ public Flux<ByteBuffer> getBody() { return body == null ? null : body.toFluxByteBuffer(); } /** * Get the request content. * * @return the content to be sent */ public BinaryData getBodyAsBinaryData() { return body; } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(String content) { return setBody(BinaryData.fromString(content)); } /** * Set the request content. * <p> * The Content-Length header will be set based on the given content's length. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(byte[] content) { return setBody(BinaryData.fromBytes(content)); } /** * Set request content. * <p> * Caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ /** * Set request content. * <p> * If provided content has known length, i.e. {@link BinaryData * Content-Length header is updated. Otherwise, * if provided content has unknown length, i.e. {@link BinaryData * the caller must set the Content-Length header to indicate the length of the content, or use Transfer-Encoding: * chunked. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(BinaryData content) { this.body = content; if (content != null && content.getLength() != null) { setContentLength(content.getLength()); } return this; } private void setContentLength(long contentLength) { headers.set("Content-Length", String.valueOf(contentLength)); } /** * Creates a copy of the request. * * The main purpose of this is so that this HttpRequest can be changed and the resulting HttpRequest can be a * backup. This means that the cloned HttpHeaders and body must not be able to change from side effects of this * HttpRequest. * * @return a new HTTP request instance with cloned instances of all mutable properties. */ public HttpRequest copy() { final HttpHeaders bufferedHeaders = new HttpHeaders(headers); return new HttpRequest(httpMethod, url, bufferedHeaders, body); } }
Wrapped within client retry policy, so can have retries when failed to get the addresses back from gateway. Does it make sense?
public Flux<OpenConnectionResponse> openConnectionsAndInitCaches(String containerLink) { checkArgument(StringUtils.isNotEmpty(containerLink), "Argument 'containerLink' should not be null nor empty"); DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> this.storeModel.openConnectionsAndInitCaches(containerLink), retryPolicyInstance); }
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
public Flux<OpenConnectionResponse> openConnectionsAndInitCaches(String containerLink) { checkArgument(StringUtils.isNotEmpty(containerLink), "Argument 'containerLink' should not be null nor empty"); return this.storeModel.openConnectionsAndInitCaches(containerLink); }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private ApiType apiType; private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length <= 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE)); this.apiType = apiType; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager); } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { ((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); ((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache); ((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); ((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry ); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public URI getWriteEndpoint() { return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null); } @Override public URI getReadEndpoint() { return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null); } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getCorrelationActivityId(options); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId), invalidPartitionExceptionRetryPolicy); } private <T> Flux<FeedResponse<T>> createQueryInternal( String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; return iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, CosmosQueryRequestOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if(options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null && options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } public static PartitionKeyInternal extractPartitionKeyValueFromDocument( InternalObjectNode document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { switch (partitionKeyDefinition.getKind()) { case HASH: String path = partitionKeyDefinition.getPaths().iterator().next(); List<String> parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts); if (value == null || value.getClass() == ObjectNode.class) { value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } if (value instanceof PartitionKeyInternal) { return (PartitionKeyInternal) value; } else { return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); } } break; case MULTI_HASH: Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()]; for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){ String partitionPath = partitionKeyDefinition.getPaths().get(pathIter); List<String> partitionPathParts = PathParser.getPathParts(partitionPath); partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts); } return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false); default: throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind()); } } return null; } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeaders(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { populateHeaders(request, RequestVerb.PATCH); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(request).processMessage(request); } @Override public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance); } private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert); Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs.flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs.flatMap(req -> patch(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs); return requestObs.flatMap(req -> this .delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> { return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); }); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, CosmosQueryRequestOptions options, Class<T> klass) { String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } itemIdentityList .forEach(itemIdentity -> { String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap; rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); return createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); double requestCharge = 0; for (FeedResponse<Document> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList())); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponse(finalList, headers); return frp; }); }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); String partitionKeySelector = createPkSelector(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame( List<CosmosItemIdentity> idPartitionKeyPairList, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); if (!Objects.equals(idValue, pkValue)) { continue; } parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkParamName = "@param" + (2 * i); parameters.add(new SqlParameter(pkParamName, pkValue)); String idValue = itemIdentity.getId(); String idParamName = "@param" + (2 * i + 1); parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.joining()); } private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum); return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, CosmosQueryRequestOptions options, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options, classOfT); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); String pkSelector = createPkSelector(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); final CosmosQueryRequestOptions effectiveOptions = ModelBridgeInternal.createQueryRequestOptions(options); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId); }); }, invalidPartitionExceptionRetryPolicy); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); return request; } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, List<Object> procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return readFeed(options, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, CosmosQueryRequestOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> readFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new CosmosQueryRequestOptions(); } Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options); int maxPageSize = maxItemCount != null ? maxItemCount : -1; final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options; DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage( response, ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getItemFactoryMethod(finalCosmosQueryRequestOptions, klass), klass)), retryPolicy); return Paginator.getPaginatedQueryResultAsObservable( options, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } @Override public DatabaseAccount getLatestDatabaseAccount() { return this.globalEndpointManager.getLatestDatabaseAccount(); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.UseGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); this.storeModel.enableThroughputControl(throughputControlStore); } this.throughputControlStore.enableThroughputControlGroup(group); } @Override private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey); String pkParamName = "@pkValue"; parameters.add(new SqlParameter(pkParamName, pkValue)); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) { logger.debug("getFeedRange collectionLink=[{}]", collectionLink); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private ApiType apiType; private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length <= 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = new ConcurrentHashMap<>(); this.apiType = apiType; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { return BridgeInternal.createCosmosDiagnostics(this); } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { ((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); ((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache); ((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); ((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry, this.globalEndpointManager ); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig.toDiagnosticsString()); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public URI getWriteEndpoint() { return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null); } @Override public URI getReadEndpoint() { return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null); } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getCorrelationActivityId(options); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId), invalidPartitionExceptionRetryPolicy); } private <T> Flux<FeedResponse<T>> createQueryInternal( String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; return iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, CosmosQueryRequestOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if(options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null && options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } public static PartitionKeyInternal extractPartitionKeyValueFromDocument( InternalObjectNode document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { switch (partitionKeyDefinition.getKind()) { case HASH: String path = partitionKeyDefinition.getPaths().iterator().next(); List<String> parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts); if (value == null || value.getClass() == ObjectNode.class) { value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } if (value instanceof PartitionKeyInternal) { return (PartitionKeyInternal) value; } else { return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); } } break; case MULTI_HASH: Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()]; for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){ String partitionPath = partitionKeyDefinition.getPaths().get(pathIter); List<String> partitionPathParts = PathParser.getPathParts(partitionPath); partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts); } return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false); default: throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind()); } } return null; } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } /** * NOTE: Caller needs to consume it by subscribing to this Mono in order for the request to populate headers * @param request request to populate headers to * @param httpMethod http method * @return Mono, which on subscription will populate the headers in the request passed in the argument. */ private Mono<RxDocumentServiceRequest> populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PATCH) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } @Override public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance); } private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert); Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs.flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs.flatMap(req -> patch(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs); return requestObs.flatMap(req -> this .delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> { return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); }); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, CosmosQueryRequestOptions options, Class<T> klass) { String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } itemIdentityList .forEach(itemIdentity -> { String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap; rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); return createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); double requestCharge = 0; for (FeedResponse<Document> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList())); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponse(finalList, headers); return frp; }); }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); String partitionKeySelector = createPkSelector(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame( List<CosmosItemIdentity> idPartitionKeyPairList, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); if (!Objects.equals(idValue, pkValue)) { continue; } parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkParamName = "@param" + (2 * i); parameters.add(new SqlParameter(pkParamName, pkValue)); String idValue = itemIdentity.getId(); String idParamName = "@param" + (2 * i + 1); parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.joining()); } private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum); return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, CosmosQueryRequestOptions options, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options, classOfT); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); String pkSelector = createPkSelector(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); final CosmosQueryRequestOptions effectiveOptions = ModelBridgeInternal.createQueryRequestOptions(options); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId); }); }, invalidPartitionExceptionRetryPolicy); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); return request; } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, List<Object> procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return readFeed(options, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, CosmosQueryRequestOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> readFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new CosmosQueryRequestOptions(); } Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options); int maxPageSize = maxItemCount != null ? maxItemCount : -1; final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options; DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage( response, ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getItemFactoryMethod(finalCosmosQueryRequestOptions, klass), klass)), retryPolicy); return Paginator.getPaginatedQueryResultAsObservable( options, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } @Override public DatabaseAccount getLatestDatabaseAccount() { return this.globalEndpointManager.getLatestDatabaseAccount(); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.UseGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); this.storeModel.enableThroughputControl(throughputControlStore); } this.throughputControlStore.enableThroughputControlGroup(group); } @Override private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey); String pkParamName = "@pkValue"; parameters.add(new SqlParameter(pkParamName, pkValue)); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) { logger.debug("getFeedRange collectionLink=[{}]", collectionLink); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } }
Yes, we need the gateway addresses anyway at some point, better to retry here and fail if we can't retrieve them.
public Flux<OpenConnectionResponse> openConnectionsAndInitCaches(String containerLink) { checkArgument(StringUtils.isNotEmpty(containerLink), "Argument 'containerLink' should not be null nor empty"); DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> this.storeModel.openConnectionsAndInitCaches(containerLink), retryPolicyInstance); }
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
public Flux<OpenConnectionResponse> openConnectionsAndInitCaches(String containerLink) { checkArgument(StringUtils.isNotEmpty(containerLink), "Argument 'containerLink' should not be null nor empty"); return this.storeModel.openConnectionsAndInitCaches(containerLink); }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private ApiType apiType; private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length <= 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE)); this.apiType = apiType; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager); } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { ((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); ((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache); ((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); ((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry ); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public URI getWriteEndpoint() { return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null); } @Override public URI getReadEndpoint() { return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null); } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getCorrelationActivityId(options); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId), invalidPartitionExceptionRetryPolicy); } private <T> Flux<FeedResponse<T>> createQueryInternal( String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; return iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, CosmosQueryRequestOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if(options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null && options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } public static PartitionKeyInternal extractPartitionKeyValueFromDocument( InternalObjectNode document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { switch (partitionKeyDefinition.getKind()) { case HASH: String path = partitionKeyDefinition.getPaths().iterator().next(); List<String> parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts); if (value == null || value.getClass() == ObjectNode.class) { value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } if (value instanceof PartitionKeyInternal) { return (PartitionKeyInternal) value; } else { return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); } } break; case MULTI_HASH: Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()]; for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){ String partitionPath = partitionKeyDefinition.getPaths().get(pathIter); List<String> partitionPathParts = PathParser.getPathParts(partitionPath); partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts); } return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false); default: throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind()); } } return null; } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeaders(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { populateHeaders(request, RequestVerb.PATCH); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(request).processMessage(request); } @Override public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance); } private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert); Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs.flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs.flatMap(req -> patch(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs); return requestObs.flatMap(req -> this .delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> { return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); }); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, CosmosQueryRequestOptions options, Class<T> klass) { String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } itemIdentityList .forEach(itemIdentity -> { String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap; rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); return createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); double requestCharge = 0; for (FeedResponse<Document> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList())); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponse(finalList, headers); return frp; }); }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); String partitionKeySelector = createPkSelector(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame( List<CosmosItemIdentity> idPartitionKeyPairList, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); if (!Objects.equals(idValue, pkValue)) { continue; } parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkParamName = "@param" + (2 * i); parameters.add(new SqlParameter(pkParamName, pkValue)); String idValue = itemIdentity.getId(); String idParamName = "@param" + (2 * i + 1); parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.joining()); } private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum); return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, CosmosQueryRequestOptions options, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options, classOfT); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); String pkSelector = createPkSelector(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); final CosmosQueryRequestOptions effectiveOptions = ModelBridgeInternal.createQueryRequestOptions(options); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId); }); }, invalidPartitionExceptionRetryPolicy); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); return request; } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, List<Object> procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return readFeed(options, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, CosmosQueryRequestOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> readFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new CosmosQueryRequestOptions(); } Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options); int maxPageSize = maxItemCount != null ? maxItemCount : -1; final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options; DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage( response, ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getItemFactoryMethod(finalCosmosQueryRequestOptions, klass), klass)), retryPolicy); return Paginator.getPaginatedQueryResultAsObservable( options, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } @Override public DatabaseAccount getLatestDatabaseAccount() { return this.globalEndpointManager.getLatestDatabaseAccount(); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.UseGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); this.storeModel.enableThroughputControl(throughputControlStore); } this.throughputControlStore.enableThroughputControlGroup(group); } @Override private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey); String pkParamName = "@pkValue"; parameters.add(new SqlParameter(pkParamName, pkValue)); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) { logger.debug("getFeedRange collectionLink=[{}]", collectionLink); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private ApiType apiType; private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length <= 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = new ConcurrentHashMap<>(); this.apiType = apiType; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { return BridgeInternal.createCosmosDiagnostics(this); } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { ((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); ((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache); ((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); ((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry, this.globalEndpointManager ); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig.toDiagnosticsString()); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public URI getWriteEndpoint() { return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null); } @Override public URI getReadEndpoint() { return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null); } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getCorrelationActivityId(options); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId), invalidPartitionExceptionRetryPolicy); } private <T> Flux<FeedResponse<T>> createQueryInternal( String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; return iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, CosmosQueryRequestOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if(options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null && options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } public static PartitionKeyInternal extractPartitionKeyValueFromDocument( InternalObjectNode document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { switch (partitionKeyDefinition.getKind()) { case HASH: String path = partitionKeyDefinition.getPaths().iterator().next(); List<String> parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts); if (value == null || value.getClass() == ObjectNode.class) { value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } if (value instanceof PartitionKeyInternal) { return (PartitionKeyInternal) value; } else { return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); } } break; case MULTI_HASH: Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()]; for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){ String partitionPath = partitionKeyDefinition.getPaths().get(pathIter); List<String> partitionPathParts = PathParser.getPathParts(partitionPath); partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts); } return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false); default: throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind()); } } return null; } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } /** * NOTE: Caller needs to consume it by subscribing to this Mono in order for the request to populate headers * @param request request to populate headers to * @param httpMethod http method * @return Mono, which on subscription will populate the headers in the request passed in the argument. */ private Mono<RxDocumentServiceRequest> populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PATCH) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } @Override public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance); } private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert); Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs.flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs.flatMap(req -> patch(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs); return requestObs.flatMap(req -> this .delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> { return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); }); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, CosmosQueryRequestOptions options, Class<T> klass) { String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } itemIdentityList .forEach(itemIdentity -> { String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap; rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); return createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); double requestCharge = 0; for (FeedResponse<Document> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList())); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponse(finalList, headers); return frp; }); }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); String partitionKeySelector = createPkSelector(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame( List<CosmosItemIdentity> idPartitionKeyPairList, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); if (!Objects.equals(idValue, pkValue)) { continue; } parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkParamName = "@param" + (2 * i); parameters.add(new SqlParameter(pkParamName, pkValue)); String idValue = itemIdentity.getId(); String idParamName = "@param" + (2 * i + 1); parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.joining()); } private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum); return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, CosmosQueryRequestOptions options, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options, classOfT); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); String pkSelector = createPkSelector(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); final CosmosQueryRequestOptions effectiveOptions = ModelBridgeInternal.createQueryRequestOptions(options); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId); }); }, invalidPartitionExceptionRetryPolicy); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); return request; } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, List<Object> procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return readFeed(options, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, CosmosQueryRequestOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> readFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new CosmosQueryRequestOptions(); } Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options); int maxPageSize = maxItemCount != null ? maxItemCount : -1; final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options; DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage( response, ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getItemFactoryMethod(finalCosmosQueryRequestOptions, klass), klass)), retryPolicy); return Paginator.getPaginatedQueryResultAsObservable( options, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } @Override public DatabaseAccount getLatestDatabaseAccount() { return this.globalEndpointManager.getLatestDatabaseAccount(); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.UseGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); this.storeModel.enableThroughputControl(throughputControlStore); } this.throughputControlStore.enableThroughputControlGroup(group); } @Override private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey); String pkParamName = "@pkValue"; parameters.add(new SqlParameter(pkParamName, pkValue)); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) { logger.debug("getFeedRange collectionLink=[{}]", collectionLink); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } }
I do not think we should reuse the clientRetryPolicy, because it may cause the SDK to failover to a different region. So added a new OpenConnectionAndInitCachesRetryPolicy to only retry on 1. gateway timeout for address resolution 2. 429
public Flux<OpenConnectionResponse> openConnectionsAndInitCaches(String containerLink) { checkArgument(StringUtils.isNotEmpty(containerLink), "Argument 'containerLink' should not be null nor empty"); DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> this.storeModel.openConnectionsAndInitCaches(containerLink), retryPolicyInstance); }
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
public Flux<OpenConnectionResponse> openConnectionsAndInitCaches(String containerLink) { checkArgument(StringUtils.isNotEmpty(containerLink), "Argument 'containerLink' should not be null nor empty"); return this.storeModel.openConnectionsAndInitCaches(containerLink); }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private ApiType apiType; private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length <= 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE)); this.apiType = apiType; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager); } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { ((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); ((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache); ((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); ((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry ); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public URI getWriteEndpoint() { return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null); } @Override public URI getReadEndpoint() { return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null); } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getCorrelationActivityId(options); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId), invalidPartitionExceptionRetryPolicy); } private <T> Flux<FeedResponse<T>> createQueryInternal( String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; return iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, CosmosQueryRequestOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if(options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null && options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } public static PartitionKeyInternal extractPartitionKeyValueFromDocument( InternalObjectNode document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { switch (partitionKeyDefinition.getKind()) { case HASH: String path = partitionKeyDefinition.getPaths().iterator().next(); List<String> parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts); if (value == null || value.getClass() == ObjectNode.class) { value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } if (value instanceof PartitionKeyInternal) { return (PartitionKeyInternal) value; } else { return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); } } break; case MULTI_HASH: Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()]; for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){ String partitionPath = partitionKeyDefinition.getPaths().get(pathIter); List<String> partitionPathParts = PathParser.getPathParts(partitionPath); partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts); } return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false); default: throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind()); } } return null; } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeaders(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeaders(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { populateHeaders(request, RequestVerb.PATCH); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(request).processMessage(request); } @Override public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance); } private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert); Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs.flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs.flatMap(req -> patch(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs); return requestObs.flatMap(req -> this .delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> { return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); }); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, CosmosQueryRequestOptions options, Class<T> klass) { String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } itemIdentityList .forEach(itemIdentity -> { String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap; rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); return createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); double requestCharge = 0; for (FeedResponse<Document> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList())); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponse(finalList, headers); return frp; }); }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); String partitionKeySelector = createPkSelector(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame( List<CosmosItemIdentity> idPartitionKeyPairList, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); if (!Objects.equals(idValue, pkValue)) { continue; } parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkParamName = "@param" + (2 * i); parameters.add(new SqlParameter(pkParamName, pkValue)); String idValue = itemIdentity.getId(); String idParamName = "@param" + (2 * i + 1); parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.joining()); } private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum); return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, CosmosQueryRequestOptions options, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options, classOfT); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); String pkSelector = createPkSelector(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); final CosmosQueryRequestOptions effectiveOptions = ModelBridgeInternal.createQueryRequestOptions(options); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId); }); }, invalidPartitionExceptionRetryPolicy); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); return request; } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, List<Object> procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return readFeed(options, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, CosmosQueryRequestOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> readFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new CosmosQueryRequestOptions(); } Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options); int maxPageSize = maxItemCount != null ? maxItemCount : -1; final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options; DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage( response, ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getItemFactoryMethod(finalCosmosQueryRequestOptions, klass), klass)), retryPolicy); return Paginator.getPaginatedQueryResultAsObservable( options, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } @Override public DatabaseAccount getLatestDatabaseAccount() { return this.globalEndpointManager.getLatestDatabaseAccount(); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.UseGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); this.storeModel.enableThroughputControl(throughputControlStore); } this.throughputControlStore.enableThroughputControlGroup(group); } @Override private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey); String pkParamName = "@pkValue"; parameters.add(new SqlParameter(pkParamName, pkValue)); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) { logger.debug("getFeedRange collectionLink=[{}]", collectionLink); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private ApiType apiType; private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length <= 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType) { activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = new ConcurrentHashMap<>(); this.apiType = apiType; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { return BridgeInternal.createCosmosDiagnostics(this); } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { ((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); ((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache); ((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); ((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry, this.globalEndpointManager ); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig.toDiagnosticsString()); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public URI getWriteEndpoint() { return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null); } @Override public URI getReadEndpoint() { return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null); } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getCorrelationActivityId(options); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId), invalidPartitionExceptionRetryPolicy); } private <T> Flux<FeedResponse<T>> createQueryInternal( String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; return iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, CosmosQueryRequestOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if(options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null && options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } public static PartitionKeyInternal extractPartitionKeyValueFromDocument( InternalObjectNode document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { switch (partitionKeyDefinition.getKind()) { case HASH: String path = partitionKeyDefinition.getPaths().iterator().next(); List<String> parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts); if (value == null || value.getClass() == ObjectNode.class) { value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } if (value instanceof PartitionKeyInternal) { return (PartitionKeyInternal) value; } else { return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); } } break; case MULTI_HASH: Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()]; for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){ String partitionPath = partitionKeyDefinition.getPaths().get(pathIter); List<String> partitionPathParts = PathParser.getPathParts(partitionPath); partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts); } return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false); default: throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind()); } } return null; } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } /** * NOTE: Caller needs to consume it by subscribing to this Mono in order for the request to populate headers * @param request request to populate headers to * @param httpMethod http method * @return Mono, which on subscription will populate the headers in the request passed in the argument. */ private Mono<RxDocumentServiceRequest> populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PATCH) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } @Override public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance); } private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert); Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs.flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs.flatMap(req -> patch(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs); return requestObs.flatMap(req -> this .delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> { return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); }); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, CosmosQueryRequestOptions options, Class<T> klass) { String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } itemIdentityList .forEach(itemIdentity -> { String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap; rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); return createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); double requestCharge = 0; for (FeedResponse<Document> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList())); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponse(finalList, headers); return frp; }); }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); String partitionKeySelector = createPkSelector(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame( List<CosmosItemIdentity> idPartitionKeyPairList, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); if (!Objects.equals(idValue, pkValue)) { continue; } parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkParamName = "@param" + (2 * i); parameters.add(new SqlParameter(pkParamName, pkValue)); String idValue = itemIdentity.getId(); String idParamName = "@param" + (2 * i + 1); parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.joining()); } private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum); return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, CosmosQueryRequestOptions options, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options, classOfT); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); String pkSelector = createPkSelector(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); final CosmosQueryRequestOptions effectiveOptions = ModelBridgeInternal.createQueryRequestOptions(options); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { throw new IllegalStateException("Failed to get routing map."); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId); }); }, invalidPartitionExceptionRetryPolicy); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); return request; } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, List<Object> procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return readFeed(options, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, CosmosQueryRequestOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> readFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new CosmosQueryRequestOptions(); } Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options); int maxPageSize = maxItemCount != null ? maxItemCount : -1; final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options; DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage( response, ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getItemFactoryMethod(finalCosmosQueryRequestOptions, klass), klass)), retryPolicy); return Paginator.getPaginatedQueryResultAsObservable( options, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } @Override public DatabaseAccount getLatestDatabaseAccount() { return this.globalEndpointManager.getLatestDatabaseAccount(); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.UseGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); this.storeModel.enableThroughputControl(throughputControlStore); } this.throughputControlStore.enableThroughputControlGroup(group); } @Override private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey); String pkParamName = "@pkValue"; parameters.add(new SqlParameter(pkParamName, pkValue)); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) { logger.debug("getFeedRange collectionLink=[{}]", collectionLink); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { throw new IllegalStateException("Collection cannot be null"); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } }
reformat this line.
List<VcapPojo> parseVcapService(String vcapServices) { final List<VcapPojo> results = new ArrayList<>(); log("VcapParser.parse: vcapServices = " + vcapServices); if (StringUtils.hasText(vcapServices)) { try { final JsonParser parser = JsonParserFactory.getJsonParser(); final Map<String, Object> servicesMap = parser.parseMap(vcapServices); final Set<Map.Entry<String, Object>> services = servicesMap.entrySet(); Assert.notNull(services, "Services entrySet cannot be null."); for (final Map.Entry<String, Object> serviceEntry : services) { final String name = serviceEntry.getKey(); if (name.startsWith(AZURE) || USER_PROVIDED.equals(name)) { Assert.isInstanceOf(List.class, serviceEntry.getValue()); final List<VcapServiceConfig> azureServices = getVcapServiceConfigList(serviceEntry.getValue()); results.addAll( azureServices.stream() .map(service -> parseService(name, service, vcapServices)) .filter(Objects::nonNull).collect(Collectors.toList()) ); } } } catch (JsonParseException e) { LOGGER.error("Error parsing " + vcapServices, e); } } return results; }
.filter(Objects::nonNull).collect(Collectors.toList())
List<VcapPojo> parseVcapService(String vcapServices) { final List<VcapPojo> results = new ArrayList<>(); log("VcapParser.parse: vcapServices = " + vcapServices); if (StringUtils.hasText(vcapServices)) { try { final JsonParser parser = JsonParserFactory.getJsonParser(); final Map<String, Object> servicesMap = parser.parseMap(vcapServices); final Set<Map.Entry<String, Object>> services = servicesMap.entrySet(); Assert.notNull(services, "Services entrySet cannot be null."); for (final Map.Entry<String, Object> serviceEntry : services) { final String name = serviceEntry.getKey(); if (name.startsWith(AZURE) || USER_PROVIDED.equals(name)) { Assert.isInstanceOf(List.class, serviceEntry.getValue()); final List<VcapServiceConfig> azureServices = getVcapServiceConfigList(serviceEntry.getValue()); results.addAll( azureServices.stream() .map(service -> parseService(name, service, vcapServices)) .filter(Objects::nonNull).collect(Collectors.toList()) ); } } } catch (JsonParseException e) { LOGGER.error("Error parsing " + vcapServices, e); } } return results; }
class VcapProcessor implements EnvironmentPostProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(VcapProcessor.class); /** * VCAP services */ private static final String VCAP_SERVICES = "VCAP_SERVICES"; /** * Log variable */ private static final String LOG_VARIABLE = "COM_MICROSOFT_AZURE_CLOUDFOUNDRY_SERVICE_LOG"; private static final String AZURE = "azure-"; private static final String USER_PROVIDED = "user-provided"; private static final String AZURE_SERVICE_BROKER_NAME = "azure-service-broker-name"; private static final String AZURE_SERVICE_PLAN = "azure-service-plan"; private static final String CREDENTIALS = "credentials"; private boolean logFlag = false; @Override public void postProcessEnvironment(ConfigurableEnvironment confEnv, SpringApplication app) { final Map<String, Object> environment = confEnv.getSystemEnvironment(); final String logValue = (String) environment.get(LOG_VARIABLE); if ("true".equals(logValue)) { logFlag = true; } log("VcapParser.postProcessEnvironment: Start"); final String vcapServices = (String) environment.get(VCAP_SERVICES); final List<VcapPojo> vcapPojos = parseVcapService(vcapServices); new VcapResult(confEnv, vcapPojos.toArray(new VcapPojo[0]), logFlag); log("VcapParser.postProcessEnvironment: End"); } @SuppressWarnings("unchecked") private VcapServiceConfig getVcapServiceConfig(@NonNull Map<String, Object> configMap) { final VcapServiceConfig serviceConfig = new VcapServiceConfig(); serviceConfig.setLabel((String) configMap.getOrDefault("label", null)); serviceConfig.setName((String) configMap.getOrDefault("name", null)); serviceConfig.setProvider((String) configMap.getOrDefault("provider", null)); serviceConfig.setSyslogDrainUrl((String) configMap.getOrDefault("syslog_drain_url", null)); serviceConfig.setPlan((String) configMap.getOrDefault("plan", null)); final List<String> tags = (List<String>) configMap.get("tags"); final List<String> volumeMounts = (List<String>) configMap.get("volume_mounts"); if (tags != null) { serviceConfig.setTags(tags.toArray(new String[0])); } if (volumeMounts != null) { serviceConfig.setVolumeMounts(volumeMounts.toArray(new String[0])); } serviceConfig.setCredentials((Map<String, String>) configMap.get(CREDENTIALS)); return serviceConfig; } private List<VcapServiceConfig> getVcapServiceConfigList(@NonNull Object value) { Assert.isInstanceOf(List.class, value); @SuppressWarnings("unchecked") final List<Map<String, Object>> configs = (List<Map<String, Object>>) value; return configs.stream().map(this::getVcapServiceConfig).collect(Collectors.toList()); } /** * Parses the VCap service. * * @param vcapServices the VCap service * @return the list of Vcap POJOs */ private VcapPojo parseService(String serviceBrokerName, VcapServiceConfig serviceConfig, String vCapServices) { final VcapPojo result = new VcapPojo(); final Map<String, String> credentials = serviceConfig.getCredentials(); if (USER_PROVIDED.equals(serviceBrokerName)) { if (credentials == null) { return null; } final String userServiceBrokerName = credentials.remove(AZURE_SERVICE_BROKER_NAME); if (userServiceBrokerName == null) { return null; } result.setServiceBrokerName(userServiceBrokerName); final String userServicePlan = credentials.remove(AZURE_SERVICE_PLAN); serviceConfig.setPlan(userServicePlan); serviceConfig.setCredentials(credentials); } else { result.setServiceBrokerName(serviceBrokerName); serviceConfig.setPlan(serviceConfig.getPlan()); if (credentials == null) { LOGGER.error("Found {}, but missing {} : {}", serviceBrokerName, CREDENTIALS, vCapServices); } } result.setServiceConfig(serviceConfig); return result; } private void log(String msg) { if (logFlag) { LOGGER.info(msg); } } }
class VcapProcessor implements EnvironmentPostProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(VcapProcessor.class); /** * VCAP services */ private static final String VCAP_SERVICES = "VCAP_SERVICES"; /** * Log variable */ private static final String LOG_VARIABLE = "COM_MICROSOFT_AZURE_CLOUDFOUNDRY_SERVICE_LOG"; private static final String AZURE = "azure-"; private static final String USER_PROVIDED = "user-provided"; private static final String AZURE_SERVICE_BROKER_NAME = "azure-service-broker-name"; private static final String AZURE_SERVICE_PLAN = "azure-service-plan"; private static final String CREDENTIALS = "credentials"; private boolean logFlag = false; @Override public void postProcessEnvironment(ConfigurableEnvironment confEnv, SpringApplication app) { final Map<String, Object> environment = confEnv.getSystemEnvironment(); final String logValue = (String) environment.get(LOG_VARIABLE); if ("true".equals(logValue)) { logFlag = true; } log("VcapParser.postProcessEnvironment: Start"); final String vcapServices = (String) environment.get(VCAP_SERVICES); final List<VcapPojo> vcapPojos = parseVcapService(vcapServices); new VcapResult(confEnv, vcapPojos.toArray(new VcapPojo[0]), logFlag); log("VcapParser.postProcessEnvironment: End"); } @SuppressWarnings("unchecked") private VcapServiceConfig getVcapServiceConfig(@NonNull Map<String, Object> configMap) { final VcapServiceConfig serviceConfig = new VcapServiceConfig(); serviceConfig.setLabel((String) configMap.getOrDefault("label", null)); serviceConfig.setName((String) configMap.getOrDefault("name", null)); serviceConfig.setProvider((String) configMap.getOrDefault("provider", null)); serviceConfig.setSyslogDrainUrl((String) configMap.getOrDefault("syslog_drain_url", null)); serviceConfig.setPlan((String) configMap.getOrDefault("plan", null)); final List<String> tags = (List<String>) configMap.get("tags"); final List<String> volumeMounts = (List<String>) configMap.get("volume_mounts"); if (tags != null) { serviceConfig.setTags(tags.toArray(new String[0])); } if (volumeMounts != null) { serviceConfig.setVolumeMounts(volumeMounts.toArray(new String[0])); } serviceConfig.setCredentials((Map<String, String>) configMap.get(CREDENTIALS)); return serviceConfig; } private List<VcapServiceConfig> getVcapServiceConfigList(@NonNull Object value) { Assert.isInstanceOf(List.class, value); @SuppressWarnings("unchecked") final List<Map<String, Object>> configs = (List<Map<String, Object>>) value; return configs.stream().map(this::getVcapServiceConfig).collect(Collectors.toList()); } /** * Parses the VCap service. * * @param vcapServices the VCap service * @return the list of Vcap POJOs */ private VcapPojo parseService(String serviceBrokerName, VcapServiceConfig serviceConfig, String vCapServices) { final VcapPojo result = new VcapPojo(); final Map<String, String> credentials = serviceConfig.getCredentials(); if (USER_PROVIDED.equals(serviceBrokerName)) { if (credentials == null) { return null; } final String userServiceBrokerName = credentials.remove(AZURE_SERVICE_BROKER_NAME); if (userServiceBrokerName == null) { return null; } result.setServiceBrokerName(userServiceBrokerName); final String userServicePlan = credentials.remove(AZURE_SERVICE_PLAN); serviceConfig.setPlan(userServicePlan); serviceConfig.setCredentials(credentials); } else { result.setServiceBrokerName(serviceBrokerName); serviceConfig.setPlan(serviceConfig.getPlan()); if (credentials == null) { LOGGER.error("Found {}, but missing {} : {}", serviceBrokerName, CREDENTIALS, vCapServices); } } result.setServiceConfig(serviceConfig); return result; } private void log(String msg) { if (logFlag) { LOGGER.info(msg); } } }
Also a merge of "if statements".
protected void configureRetry(T builder) { RetryOptionsProvider.RetryOptions retry = null; if (azureProperties instanceof RetryOptionsProvider) { retry = ((RetryOptionsProvider) azureProperties).getRetry(); } if (retry == null) { return; } if (RetryOptionsProvider.RetryMode.EXPONENTIAL == retry.getMode()) { if (retry.getExponential() != null && retry.getExponential().getMaxRetries() != null) { builder.maxRetry(retry.getExponential().getMaxRetries()); } } else if (RetryOptionsProvider.RetryMode.FIXED == retry.getMode() && retry.getFixed() != null && retry.getFixed().getMaxRetries() != null) { builder.maxRetry(retry.getFixed().getMaxRetries()); } }
}
protected void configureRetry(T builder) { RetryOptionsProvider.RetryOptions retry = null; if (azureProperties instanceof RetryOptionsProvider) { retry = ((RetryOptionsProvider) azureProperties).getRetry(); } if (retry == null) { return; } if (RetryOptionsProvider.RetryMode.EXPONENTIAL == retry.getMode()) { if (retry.getExponential() != null && retry.getExponential().getMaxRetries() != null) { builder.maxRetry(retry.getExponential().getMaxRetries()); } } else if (RetryOptionsProvider.RetryMode.FIXED == retry.getMode() && retry.getFixed() != null && retry.getFixed().getMaxRetries() != null) { builder.maxRetry(retry.getFixed().getMaxRetries()); } }
class AbstractAzureCredentialBuilderFactory<T extends CredentialBuilderBase<T>> extends AbstractAzureHttpClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureCredentialBuilderFactory.class); private final AzureProperties azureProperties; /** * To create a {@link AbstractAzureCredentialBuilderFactory} instance with {@link AzureProperties}. * @param azureProperties The Azure properties. */ protected AbstractAzureCredentialBuilderFactory(AzureProperties azureProperties) { this.azureProperties = azureProperties; } @Override protected BiConsumer<T, HttpClient> consumeHttpClient() { return T::httpClient; } @Override protected BiConsumer<T, HttpPipeline> consumeHttpPipeline() { return T::httpPipeline; } @Override protected AzureProperties getAzureProperties() { return this.azureProperties; } @Override protected BiConsumer<T, Configuration> consumeConfiguration() { return T::configuration; } @Override @Override protected List<AuthenticationDescriptor<?>> getAuthenticationDescriptors(T builder) { return Collections.emptyList(); } @Override protected BiConsumer<T, ClientOptions> consumeClientOptions() { return (a, b) -> { }; } @Override protected BiConsumer<T, TokenCredential> consumeDefaultTokenCredential() { return (a, b) -> { }; } @Override protected BiConsumer<T, String> consumeConnectionString() { return (a, b) -> { }; } @Override protected BiConsumer<T, HttpLogOptions> consumeHttpLogOptions() { return (a, b) -> { }; } @Override protected BiConsumer<T, HttpPipelinePolicy> consumeHttpPipelinePolicy() { return (a, b) -> { }; } @Override protected BiConsumer<T, RetryPolicy> consumeRetryPolicy() { LOGGER.debug("No need to specify retry policy."); return (a, b) -> { }; } @Override protected void configureService(T builder) { } }
class AbstractAzureCredentialBuilderFactory<T extends CredentialBuilderBase<T>> extends AbstractAzureHttpClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureCredentialBuilderFactory.class); private final AzureProperties azureProperties; /** * To create a {@link AbstractAzureCredentialBuilderFactory} instance with {@link AzureProperties}. * @param azureProperties The Azure properties. */ protected AbstractAzureCredentialBuilderFactory(AzureProperties azureProperties) { this.azureProperties = azureProperties; } @Override protected BiConsumer<T, HttpClient> consumeHttpClient() { return T::httpClient; } @Override protected BiConsumer<T, HttpPipeline> consumeHttpPipeline() { return T::httpPipeline; } @Override protected AzureProperties getAzureProperties() { return this.azureProperties; } @Override protected BiConsumer<T, Configuration> consumeConfiguration() { return T::configuration; } @Override @Override protected List<AuthenticationDescriptor<?>> getAuthenticationDescriptors(T builder) { return Collections.emptyList(); } @Override protected BiConsumer<T, ClientOptions> consumeClientOptions() { return (a, b) -> { }; } @Override protected BiConsumer<T, TokenCredential> consumeDefaultTokenCredential() { return (a, b) -> { }; } @Override protected BiConsumer<T, String> consumeConnectionString() { return (a, b) -> { }; } @Override protected BiConsumer<T, HttpLogOptions> consumeHttpLogOptions() { return (a, b) -> { }; } @Override protected BiConsumer<T, HttpPipelinePolicy> consumeHttpPipelinePolicy() { return (a, b) -> { }; } @Override protected BiConsumer<T, RetryPolicy> consumeRetryPolicy() { LOGGER.debug("No need to specify retry policy."); return (a, b) -> { }; } @Override protected void configureService(T builder) { } }
local var "destination" hide field name will bring reading confusion. Use "dest" here for clarity and shortness. Besides, Does "getDesitnation(message)" looks more reasonable.
protected void handleMessageInternal(Message<?> message) { String dest = toDestination(message); Map<String, String> partitionHeaders = getPartitionFromExpression(message); Message<?> messageToSend = createMutableMessage(message, partitionHeaders); final Mono<Void> mono = this.sendOperation.sendAsync(dest, messageToSend); if (this.sync) { waitingSendResponse(mono, message); } else { handleSendResponseAsync(mono, message); } }
String dest = toDestination(message);
protected void handleMessageInternal(Message<?> message) { String dest = toDestination(message); Map<String, String> partitionHeaders = getPartitionFromExpression(message); Message<?> messageToSend = createMutableMessage(message, partitionHeaders); final Mono<Void> mono = this.sendOperation.sendAsync(dest, messageToSend); if (this.sync) { waitingSendResponse(mono, message); } else { handleSendResponseAsync(mono, message); } }
class DefaultMessageHandler extends AbstractMessageProducingHandler { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageHandler.class); private static final long DEFAULT_SEND_TIMEOUT = 10000; private final String destination; private final SendOperation sendOperation; private boolean sync = false; private ListenableFutureCallback<Void> sendCallback; private EvaluationContext evaluationContext; private Expression sendTimeoutExpression = new ValueExpression<>(DEFAULT_SEND_TIMEOUT); private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy(); private Expression partitionKeyExpression; private Expression partitionIdExpression; private MessageChannel sendFailureChannel; private String sendFailureChannelName; /** * Construct a {@link DefaultMessageHandler} with the specified destination and sendOperation. * * @param destination the destination * @param sendOperation operation for sending Messages to a destination */ public DefaultMessageHandler(String destination, @NonNull SendOperation sendOperation) { Assert.hasText(destination, "destination can't be null or empty"); this.destination = destination; this.sendOperation = sendOperation; } @Override protected void onInit() { super.onInit(); this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); LOGGER.info("Started DefaultMessageHandler with properties: {}", buildPropertiesMap()); } @Override private <T> void handleSendResponseAsync(Mono<T> mono, Message<?> message) { mono.doOnError(ex -> { if (LOGGER.isWarnEnabled()) { LOGGER.warn("{} sent failed in async mode due to {}", message, ex.getMessage()); } if (this.sendCallback != null) { this.sendCallback.onFailure(ex); } if (getSendFailureChannel() != null) { this.messagingTemplate.send(getSendFailureChannel(), getErrorMessageStrategy() .buildErrorMessage(new AzureSendFailureException(message, ex), null)); } }).doOnSuccess(t -> { if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} sent successfully in async mode", message); } if (this.sendCallback != null) { this.sendCallback.onSuccess((Void) t); } }).subscribe(); } private <T> void waitingSendResponse(Mono<T> mono, Message<?> message) { Long sendTimeout = this.sendTimeoutExpression.getValue(this.evaluationContext, message, Long.class); if (sendTimeout == null || sendTimeout < 0) { try { mono.block(); } catch (Exception e) { throw new MessageDeliveryException(e.getMessage()); } } else { try { mono.block(Duration.of(sendTimeout, ChronoUnit.MILLIS)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} sent successfully in sync mode", message); } } catch (Exception e) { if (e.getCause() instanceof TimeoutException) { throw new MessageTimeoutException(message, "Timeout waiting for send event hub response"); } throw new MessageDeliveryException(e.getMessage()); } } } /** * Set sync. * * @param sync the sync */ public void setSync(boolean sync) { this.sync = sync; LOGGER.info("DefaultMessageHandler sync becomes: {}", sync); } @Override public void setSendTimeout(long sendTimeout) { setSendTimeoutExpression(new ValueExpression<>(sendTimeout)); } /** * Set partition Key. * * @param partitionKey the partition Key */ public void setPartitionKey(String partitionKey) { setPartitionKeyExpression(new LiteralExpression(partitionKey)); } /** * Set partition key expression. * * @param partitionKeyExpression the partition key expression */ public void setPartitionKeyExpression(Expression partitionKeyExpression) { this.partitionKeyExpression = partitionKeyExpression; } /** * Set partition id expression. * * @param partitionIdExpression the partition id expression */ public void setPartitionIdExpression(Expression partitionIdExpression) { this.partitionIdExpression = partitionIdExpression; } /** * Set partition key expression string. * * @param partitionKeyExpression the partition key expression */ public void setPartitionKeyExpressionString(String partitionKeyExpression) { setPartitionKeyExpression(EXPRESSION_PARSER.parseExpression(partitionKeyExpression)); } private String toDestination(Message<?> message) { if (message.getHeaders().containsKey(AzureHeaders.NAME)) { return message.getHeaders().get(AzureHeaders.NAME, String.class); } return this.destination; } /** * To create a {@link Map} for partition id and/or key values computing from the partition id and key expression * for each message to send. * @param message to generate partition id and/or key for. * @return a {@link Map} containing partition id and/or key values. */ private Map<String, String> getPartitionFromExpression(Message<?> message) { Map<String, String> partitionMap = new HashMap<>(); evaluatePartition(message, this.partitionIdExpression) .ifPresent(id -> partitionMap.put(PARTITION_ID, id)); evaluatePartition(message, this.partitionKeyExpression) .ifPresent(key -> partitionMap.put(PARTITION_KEY, key)); return partitionMap; } private Optional<String> evaluatePartition(Message<?> message, Expression expression) { return Optional.ofNullable(expression) .map(exp -> exp.getValue(this.evaluationContext, message, String.class)); } /** * Create a {@code MutableMessage} to copy the message id and timestamp headers from the raw message, and set partition * headers extracted from partition expressions when there are no partition id and/or key headers in the raw messages. * @param rawMessage the raw message to copy from. * @param partitionHeaders a map containing the partition id and/or key headers computed from the partition expressions. * @return the {@code MutableMessage}. */ private Message<?> createMutableMessage(Message<?> rawMessage, Map<String, String> partitionHeaders) { return MutableMessageBuilder.fromMessage(rawMessage) .copyHeadersIfAbsent(partitionHeaders) .build(); } private Map<String, Object> buildPropertiesMap() { Map<String, Object> properties = new HashMap<>(); properties.put("sync", sync); properties.put("sendTimeout", sendTimeoutExpression); properties.put("destination", destination); return properties; } /** * Set send call back. * * @param callback the call back */ public void setSendCallback(ListenableFutureCallback<Void> callback) { this.sendCallback = callback; } /** * Get send time out expression. * * @return sendTimeoutExpression the send time out expression */ public Expression getSendTimeoutExpression() { return sendTimeoutExpression; } /** * Set send time out expression. * * @param sendTimeoutExpression the send time out expression */ public void setSendTimeoutExpression(Expression sendTimeoutExpression) { Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null"); this.sendTimeoutExpression = sendTimeoutExpression; LOGGER.info("DefaultMessageHandler syncTimeout becomes: {}", sendTimeoutExpression); } /** * Get send failure channel. * * @return sendFailureChannel If sendFailureChannel or sendFailureChannelName is not null, null otherwise */ protected MessageChannel getSendFailureChannel() { if (this.sendFailureChannel != null) { return this.sendFailureChannel; } else if (this.sendFailureChannelName != null) { this.sendFailureChannel = getChannelResolver().resolveDestination(this.sendFailureChannelName); return this.sendFailureChannel; } return null; } /** * Set send failure channel. * * @param sendFailureChannel the send failure channel */ public void setSendFailureChannel(MessageChannel sendFailureChannel) { this.sendFailureChannel = sendFailureChannel; } /** * Set send failure channel name. * * @param sendFailureChannelName the send failure channel name */ public void setSendFailureChannelName(String sendFailureChannelName) { this.sendFailureChannelName = sendFailureChannelName; } /** * Get error message strategy. * * @return the error message strategy */ protected ErrorMessageStrategy getErrorMessageStrategy() { return this.errorMessageStrategy; } /** * Set error message strategy. * * @param errorMessageStrategy the error message strategy */ public void setErrorMessageStrategy(ErrorMessageStrategy errorMessageStrategy) { Assert.notNull(errorMessageStrategy, "'errorMessageStrategy' must not be null"); this.errorMessageStrategy = errorMessageStrategy; } }
class DefaultMessageHandler extends AbstractMessageProducingHandler { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageHandler.class); private static final long DEFAULT_SEND_TIMEOUT = 10000; private final String destination; private final SendOperation sendOperation; private boolean sync = false; private ListenableFutureCallback<Void> sendCallback; private EvaluationContext evaluationContext; private Expression sendTimeoutExpression = new ValueExpression<>(DEFAULT_SEND_TIMEOUT); private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy(); private Expression partitionKeyExpression; private Expression partitionIdExpression; private MessageChannel sendFailureChannel; private String sendFailureChannelName; /** * Construct a {@link DefaultMessageHandler} with the specified destination and sendOperation. * * @param destination the destination * @param sendOperation operation for sending Messages to a destination */ public DefaultMessageHandler(String destination, @NonNull SendOperation sendOperation) { Assert.hasText(destination, "destination can't be null or empty"); this.destination = destination; this.sendOperation = sendOperation; } @Override protected void onInit() { super.onInit(); this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); LOGGER.info("Started DefaultMessageHandler with properties: {}", buildPropertiesMap()); } @Override private <T> void handleSendResponseAsync(Mono<T> mono, Message<?> message) { mono.doOnError(ex -> { if (LOGGER.isWarnEnabled()) { LOGGER.warn("{} sent failed in async mode due to {}", message, ex.getMessage()); } if (this.sendCallback != null) { this.sendCallback.onFailure(ex); } if (getSendFailureChannel() != null) { this.messagingTemplate.send(getSendFailureChannel(), getErrorMessageStrategy() .buildErrorMessage(new AzureSendFailureException(message, ex), null)); } }).doOnSuccess(t -> { if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} sent successfully in async mode", message); } if (this.sendCallback != null) { this.sendCallback.onSuccess((Void) t); } }).subscribe(); } private <T> void waitingSendResponse(Mono<T> mono, Message<?> message) { Long sendTimeout = this.sendTimeoutExpression.getValue(this.evaluationContext, message, Long.class); if (sendTimeout == null || sendTimeout < 0) { try { mono.block(); } catch (Exception e) { throw new MessageDeliveryException(e.getMessage()); } } else { try { mono.block(Duration.of(sendTimeout, ChronoUnit.MILLIS)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} sent successfully in sync mode", message); } } catch (Exception e) { if (e.getCause() instanceof TimeoutException) { throw new MessageTimeoutException(message, "Timeout waiting for send event hub response"); } throw new MessageDeliveryException(e.getMessage()); } } } /** * Set sync. * * @param sync the sync */ public void setSync(boolean sync) { this.sync = sync; LOGGER.info("DefaultMessageHandler sync becomes: {}", sync); } @Override public void setSendTimeout(long sendTimeout) { setSendTimeoutExpression(new ValueExpression<>(sendTimeout)); } /** * Set partition Key. * * @param partitionKey the partition Key */ public void setPartitionKey(String partitionKey) { setPartitionKeyExpression(new LiteralExpression(partitionKey)); } /** * Set partition key expression. * * @param partitionKeyExpression the partition key expression */ public void setPartitionKeyExpression(Expression partitionKeyExpression) { this.partitionKeyExpression = partitionKeyExpression; } /** * Set partition id expression. * * @param partitionIdExpression the partition id expression */ public void setPartitionIdExpression(Expression partitionIdExpression) { this.partitionIdExpression = partitionIdExpression; } /** * Set partition key expression string. * * @param partitionKeyExpression the partition key expression */ public void setPartitionKeyExpressionString(String partitionKeyExpression) { setPartitionKeyExpression(EXPRESSION_PARSER.parseExpression(partitionKeyExpression)); } private String toDestination(Message<?> message) { if (message.getHeaders().containsKey(AzureHeaders.NAME)) { return message.getHeaders().get(AzureHeaders.NAME, String.class); } return this.destination; } /** * To create a {@link Map} for partition id and/or key values computing from the partition id and key expression * for each message to send. * @param message to generate partition id and/or key for. * @return a {@link Map} containing partition id and/or key values. */ private Map<String, String> getPartitionFromExpression(Message<?> message) { Map<String, String> partitionMap = new HashMap<>(); evaluatePartition(message, this.partitionIdExpression) .ifPresent(id -> partitionMap.put(PARTITION_ID, id)); evaluatePartition(message, this.partitionKeyExpression) .ifPresent(key -> partitionMap.put(PARTITION_KEY, key)); return partitionMap; } private Optional<String> evaluatePartition(Message<?> message, Expression expression) { return Optional.ofNullable(expression) .map(exp -> exp.getValue(this.evaluationContext, message, String.class)); } /** * Create a {@code MutableMessage} to copy the message id and timestamp headers from the raw message, and set partition * headers extracted from partition expressions when there are no partition id and/or key headers in the raw messages. * @param rawMessage the raw message to copy from. * @param partitionHeaders a map containing the partition id and/or key headers computed from the partition expressions. * @return the {@code MutableMessage}. */ private Message<?> createMutableMessage(Message<?> rawMessage, Map<String, String> partitionHeaders) { return MutableMessageBuilder.fromMessage(rawMessage) .copyHeadersIfAbsent(partitionHeaders) .build(); } private Map<String, Object> buildPropertiesMap() { Map<String, Object> properties = new HashMap<>(); properties.put("sync", sync); properties.put("sendTimeout", sendTimeoutExpression); properties.put("destination", destination); return properties; } /** * Set send call back. * * @param callback the call back */ public void setSendCallback(ListenableFutureCallback<Void> callback) { this.sendCallback = callback; } /** * Get send time out expression. * * @return sendTimeoutExpression the send time out expression */ public Expression getSendTimeoutExpression() { return sendTimeoutExpression; } /** * Set send time out expression. * * @param sendTimeoutExpression the send time out expression */ public void setSendTimeoutExpression(Expression sendTimeoutExpression) { Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null"); this.sendTimeoutExpression = sendTimeoutExpression; LOGGER.info("DefaultMessageHandler syncTimeout becomes: {}", sendTimeoutExpression); } /** * Get send failure channel. * * @return sendFailureChannel If sendFailureChannel or sendFailureChannelName is not null, null otherwise */ protected MessageChannel getSendFailureChannel() { if (this.sendFailureChannel != null) { return this.sendFailureChannel; } else if (this.sendFailureChannelName != null) { this.sendFailureChannel = getChannelResolver().resolveDestination(this.sendFailureChannelName); return this.sendFailureChannel; } return null; } /** * Set send failure channel. * * @param sendFailureChannel the send failure channel */ public void setSendFailureChannel(MessageChannel sendFailureChannel) { this.sendFailureChannel = sendFailureChannel; } /** * Set send failure channel name. * * @param sendFailureChannelName the send failure channel name */ public void setSendFailureChannelName(String sendFailureChannelName) { this.sendFailureChannelName = sendFailureChannelName; } /** * Get error message strategy. * * @return the error message strategy */ protected ErrorMessageStrategy getErrorMessageStrategy() { return this.errorMessageStrategy; } /** * Set error message strategy. * * @param errorMessageStrategy the error message strategy */ public void setErrorMessageStrategy(ErrorMessageStrategy errorMessageStrategy) { Assert.notNull(errorMessageStrategy, "'errorMessageStrategy' must not be null"); this.errorMessageStrategy = errorMessageStrategy; } }
I am not sure about this, but the "spotbug" hints a low risk of defect. Seems just remove the logger in this file.
protected void doStop() { if (this.delegate != null) { this.delegate.stop(); } }
if (this.delegate != null) {
protected void doStop() { if (this.delegate != null) { this.delegate.stop(); } }
class EventHubsMessageListenerContainer extends AbstractMessageListenerContainer { private final EventHubsProcessorFactory processorFactory; private final EventHubsContainerProperties containerProperties; private EventHubsErrorHandler errorHandler; private EventProcessorClient delegate; /** * Create an instance using the supplied processor factory and container properties. * * @param processorFactory the processor factory. * @param containerProperties the container properties */ public EventHubsMessageListenerContainer(EventHubsProcessorFactory processorFactory, EventHubsContainerProperties containerProperties) { this.processorFactory = processorFactory; this.containerProperties = containerProperties == null ? new EventHubsContainerProperties() : containerProperties; } @Override protected void doStart() { String eventHubName = this.containerProperties.getEventHubName(); String consumerGroup = this.containerProperties.getConsumerGroup(); if (this.errorHandler != null) { this.containerProperties.setErrorHandler(this.errorHandler); } this.delegate = this.processorFactory.createProcessor(eventHubName, consumerGroup, this.containerProperties); this.delegate.start(); } @Override @Override public void setupMessageListener(MessageListener<?> messageListener) { this.containerProperties.setMessageListener(messageListener); } @Override public EventHubsContainerProperties getContainerProperties() { return containerProperties; } /** * Set the error handler to call when the listener throws an exception. * @param errorHandler the error handler. */ public void setErrorHandler(EventHubsErrorHandler errorHandler) { this.errorHandler = errorHandler; } }
class EventHubsMessageListenerContainer extends AbstractMessageListenerContainer { private final EventHubsProcessorFactory processorFactory; private final EventHubsContainerProperties containerProperties; private EventHubsErrorHandler errorHandler; private EventProcessorClient delegate; /** * Create an instance using the supplied processor factory and container properties. * * @param processorFactory the processor factory. * @param containerProperties the container properties */ public EventHubsMessageListenerContainer(EventHubsProcessorFactory processorFactory, EventHubsContainerProperties containerProperties) { this.processorFactory = processorFactory; this.containerProperties = containerProperties == null ? new EventHubsContainerProperties() : containerProperties; } @Override protected void doStart() { String eventHubName = this.containerProperties.getEventHubName(); String consumerGroup = this.containerProperties.getConsumerGroup(); if (this.errorHandler != null) { this.containerProperties.setErrorHandler(this.errorHandler); } this.delegate = this.processorFactory.createProcessor(eventHubName, consumerGroup, this.containerProperties); this.delegate.start(); } @Override @Override public void setupMessageListener(MessageListener<?> messageListener) { this.containerProperties.setMessageListener(messageListener); } @Override public EventHubsContainerProperties getContainerProperties() { return containerProperties; } /** * Set the error handler to call when the listener throws an exception. * @param errorHandler the error handler. */ public void setErrorHandler(EventHubsErrorHandler errorHandler) { this.errorHandler = errorHandler; } }
same as above.
protected void doStop() { if (this.delegate != null) { this.delegate.stop(); } }
if (this.delegate != null) {
protected void doStop() { if (this.delegate != null) { this.delegate.stop(); } }
class ServiceBusMessageListenerContainer extends AbstractMessageListenerContainer { private final ServiceBusProcessorFactory processorFactory; private final ServiceBusContainerProperties containerProperties; private ServiceBusErrorHandler errorHandler; private ServiceBusProcessorClient delegate; /** * Create an instance using the supplied processor factory and container properties. * * @param processorFactory the processor factory. * @param containerProperties the container properties. */ public ServiceBusMessageListenerContainer(ServiceBusProcessorFactory processorFactory, ServiceBusContainerProperties containerProperties) { this.processorFactory = processorFactory; this.containerProperties = containerProperties == null ? new ServiceBusContainerProperties() : containerProperties; } @Override protected void doStart() { String entityName = containerProperties.getEntityName(); String subscriptionName = containerProperties.getSubscriptionName(); if (this.errorHandler != null) { this.containerProperties.setErrorHandler(errorHandler); } if (StringUtils.hasText(subscriptionName)) { this.delegate = this.processorFactory.createProcessor(entityName, subscriptionName, containerProperties); } else { this.delegate = this.processorFactory.createProcessor(entityName, containerProperties); } this.delegate.start(); } @Override @Override public void setupMessageListener(MessageListener<?> messageListener) { this.containerProperties.setMessageListener(messageListener); } @Override public ServiceBusContainerProperties getContainerProperties() { return containerProperties; } /** * Set the error handler to call when the listener throws an exception. * @param errorHandler the error handler. */ public void setErrorHandler(ServiceBusErrorHandler errorHandler) { this.errorHandler = errorHandler; } }
class ServiceBusMessageListenerContainer extends AbstractMessageListenerContainer { private final ServiceBusProcessorFactory processorFactory; private final ServiceBusContainerProperties containerProperties; private ServiceBusErrorHandler errorHandler; private ServiceBusProcessorClient delegate; /** * Create an instance using the supplied processor factory and container properties. * * @param processorFactory the processor factory. * @param containerProperties the container properties. */ public ServiceBusMessageListenerContainer(ServiceBusProcessorFactory processorFactory, ServiceBusContainerProperties containerProperties) { this.processorFactory = processorFactory; this.containerProperties = containerProperties == null ? new ServiceBusContainerProperties() : containerProperties; } @Override protected void doStart() { String entityName = containerProperties.getEntityName(); String subscriptionName = containerProperties.getSubscriptionName(); if (this.errorHandler != null) { this.containerProperties.setErrorHandler(errorHandler); } if (StringUtils.hasText(subscriptionName)) { this.delegate = this.processorFactory.createProcessor(entityName, subscriptionName, containerProperties); } else { this.delegate = this.processorFactory.createProcessor(entityName, containerProperties); } this.delegate.start(); } @Override @Override public void setupMessageListener(MessageListener<?> messageListener) { this.containerProperties.setMessageListener(messageListener); } @Override public ServiceBusContainerProperties getContainerProperties() { return containerProperties; } /** * Set the error handler to call when the listener throws an exception. * @param errorHandler the error handler. */ public void setErrorHandler(ServiceBusErrorHandler errorHandler) { this.errorHandler = errorHandler; } }
I don't think this check is required, in this context, it does nothing
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched", versionString); } return true; } } } return false; }
if (LOGGER.isDebugEnabled()) {
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched", versionString); return true; } } } return false; }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release"; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] section.%n" + "If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: "https: } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Version found in Boot manifest [{}]", version); if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release"; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] section.%n" + "If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: "https: } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Version found in Boot manifest [{}]", version); if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
Yes, we may not need this check in this context.
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched", versionString); } return true; } } } return false; }
if (LOGGER.isDebugEnabled()) {
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched", versionString); return true; } } } return false; }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release"; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] section.%n" + "If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: "https: } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Version found in Boot manifest [{}]", version); if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release"; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] section.%n" + "If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: "https: } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Version found in Boot manifest [{}]", version); if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
do we need this `if (LOGGER.isTraceEnabled())`?
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AopInfrastructureBean || bean instanceof MessageListenerContainerFactory || bean instanceof AzureListenerEndpointRegistry) { return bean; } Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean); if (!this.nonAnnotatedClasses.contains(targetClass)) { Map<Method, Set<T>> annotatedMethods = MethodIntrospector.selectMethods(targetClass, (MethodIntrospector.MetadataLookup<Set<T>>) method -> { Set<T> listenerMethods = findListenerMethods(method); return (!listenerMethods.isEmpty() ? listenerMethods : null); }); if (annotatedMethods.isEmpty()) { this.nonAnnotatedClasses.add(targetClass); if (LOGGER.isTraceEnabled()) { LOGGER.trace("No @AzureMessageListener annotations found on bean type: {}", targetClass); } } else { annotatedMethods.forEach((method, listeners) -> listeners .forEach(listener -> processAzureListener(listener, method, bean))); if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} @AzureMessageListener methods processed on bean '{}': {}", annotatedMethods.size(), beanName, annotatedMethods); } } } return bean; }
if (LOGGER.isTraceEnabled()) {
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AopInfrastructureBean || bean instanceof MessageListenerContainerFactory || bean instanceof AzureListenerEndpointRegistry) { return bean; } Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean); if (!this.nonAnnotatedClasses.contains(targetClass)) { Map<Method, Set<T>> annotatedMethods = MethodIntrospector.selectMethods(targetClass, (MethodIntrospector.MetadataLookup<Set<T>>) method -> { Set<T> listenerMethods = findListenerMethods(method); return (!listenerMethods.isEmpty() ? listenerMethods : null); }); if (annotatedMethods.isEmpty()) { this.nonAnnotatedClasses.add(targetClass); LOGGER.trace("No @AzureMessageListener annotations found on bean type: {}", targetClass); } else { annotatedMethods.forEach((method, listeners) -> listeners .forEach(listener -> processAzureListener(listener, method, bean))); LOGGER.debug("{} @AzureMessageListener methods processed on bean '{}': {}", annotatedMethods.size(), beanName, annotatedMethods); } } return bean; }
class AzureListenerAnnotationBeanPostProcessorAdapter<T> implements MergedBeanDefinitionPostProcessor, Ordered, BeanFactoryAware, SmartInitializingSingleton { private static final Logger LOGGER = LoggerFactory.getLogger(AzureListenerAnnotationBeanPostProcessorAdapter.class); public static final String DEFAULT_AZURE_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME = "azureListenerEndpointRegistry"; /** * The bean name of the default {@link MessageListenerContainerFactory}. */ protected String containerFactoryBeanName; private final MessageHandlerMethodFactoryAdapter messageHandlerMethodFactory = new MessageHandlerMethodFactoryAdapter(); protected final AtomicInteger counter = new AtomicInteger(); private final Set<Class<?>> nonAnnotatedClasses = Collections.newSetFromMap(new ConcurrentHashMap<>(64)); private final AzureListenerEndpointRegistrar registrar = new AzureListenerEndpointRegistrar(); @Nullable private AzureListenerEndpointRegistry endpointRegistry; @Nullable private BeanFactory beanFactory; @Nullable private StringValueResolver embeddedValueResolver; /** * Set the container factory bean name. * @param containerFactoryBeanName the container factory bean name. */ public void setContainerFactoryBeanName(String containerFactoryBeanName) { this.containerFactoryBeanName = containerFactoryBeanName; } @Override public int getOrder() { return LOWEST_PRECEDENCE; } /** * Making a {@link BeanFactory} available is optional; if not set, * {@link AzureListenerConfigurer} beans won't get autodetected and an */ @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; if (beanFactory instanceof ConfigurableBeanFactory) { this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory); } this.registrar.setBeanFactory(beanFactory); } @Override public void afterSingletonsInstantiated() { this.nonAnnotatedClasses.clear(); if (this.beanFactory instanceof ListableBeanFactory) { Map<String, AzureListenerConfigurer> beans = ((ListableBeanFactory) this.beanFactory).getBeansOfType(AzureListenerConfigurer.class); List<AzureListenerConfigurer> configurers = new ArrayList<>(beans.values()); AnnotationAwareOrderComparator.sort(configurers); for (AzureListenerConfigurer configurer : configurers) { configurer.configureAzureListeners(this.registrar); } } if (this.containerFactoryBeanName != null) { this.registrar.setContainerFactoryBeanName(this.containerFactoryBeanName); } if (this.registrar.getEndpointRegistry() == null) { if (this.endpointRegistry == null) { Assert.state(this.beanFactory != null, "BeanFactory must be set to find endpoint registry by bean name"); this.endpointRegistry = this.beanFactory.getBean(DEFAULT_AZURE_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME, AzureListenerEndpointRegistry.class); } this.registrar.setEndpointRegistry(this.endpointRegistry); } MessageHandlerMethodFactory handlerMethodFactory = this.registrar.getMessageHandlerMethodFactory(); if (handlerMethodFactory != null) { this.messageHandlerMethodFactory.setMessageHandlerMethodFactory(handlerMethodFactory); } this.registrar.afterPropertiesSet(); } @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { } /** * @throws BeansException in case of errors */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * @throws BeansException in case of errors */ @Override /** * Process the given {@link T} annotation on the given method, * registering a corresponding endpoint for the given bean instance. * * @param listenerAnnotation the annotation to process * @param mostSpecificMethod the annotated method * @param bean the instance to invoke the method on * @see AzureListenerEndpointRegistrar * @throws BeanInitializationException If no ListenerContainerFactory could be found. */ private void processAzureListener(T listenerAnnotation, Method mostSpecificMethod, Object bean) { Method invocableMethod = AopUtils.selectInvocableMethod(mostSpecificMethod, bean.getClass()); AzureListenerEndpoint endpoint = createAndConfigureMethodListenerEndpoint(listenerAnnotation, bean, invocableMethod, beanFactory, messageHandlerMethodFactory); MessageListenerContainerFactory<?> factory = null; String containerFactoryBeanNameResolved = resolve(getContainerFactoryBeanName(listenerAnnotation)); if (StringUtils.hasText(containerFactoryBeanNameResolved)) { Assert.state(this.beanFactory != null, "BeanFactory must be set to obtain container factory by bean name"); try { factory = this.beanFactory.getBean(containerFactoryBeanNameResolved, MessageListenerContainerFactory.class); } catch (NoSuchBeanDefinitionException ex) { throw new BeanInitializationException( "Could not register Azure listener endpoint on [" + mostSpecificMethod + "], no " + MessageListenerContainerFactory.class.getSimpleName() + " with id '" + containerFactoryBeanNameResolved + "' was found in the application context", ex); } } this.registrar.registerEndpoint(endpoint, factory); } protected abstract Set<T> findListenerMethods(Method method); /** * Instantiate an empty {@link AzureListenerEndpoint} and perform further * configuration with provided parameters in {@link * * @param listenerAnnotation the listener annotation * @param bean the object instance that should manage this endpoint. * @param method the method to invoke to process a message managed by this endpoint. * @param beanFactory the Spring bean factory to use to resolve expressions * @param messageHandlerMethodFactory the {@link MessageHandlerMethodFactory} to use to build the * {@link InvocableHandlerMethod} responsible to manage the invocation of * this endpoint. * * @return an {@link AzureListenerEndpoint} implementation. */ protected abstract AzureListenerEndpoint createAndConfigureMethodListenerEndpoint( T listenerAnnotation, Object bean, Method method, BeanFactory beanFactory, MessageHandlerMethodFactory messageHandlerMethodFactory); protected abstract String getEndpointId(T listenerAnnotation); protected abstract String getContainerFactoryBeanName(T listenerAnnotation); protected abstract Class<T> getListenerType(); @Nullable protected String resolve(String value) { return (this.embeddedValueResolver != null ? this.embeddedValueResolver.resolveStringValue(value) : value); } /** * A {@link MessageHandlerMethodFactory} adapter that offers a configurable underlying * instance to use. Useful if the factory to use is determined once the endpoints * have been registered but not created yet. * * @see AzureListenerEndpointRegistrar */ private class MessageHandlerMethodFactoryAdapter implements MessageHandlerMethodFactory { @Nullable private MessageHandlerMethodFactory messageHandlerMethodFactory; @Override public InvocableHandlerMethod createInvocableHandlerMethod(Object bean, Method method) { return getMessageHandlerMethodFactory().createInvocableHandlerMethod(bean, method); } private MessageHandlerMethodFactory getMessageHandlerMethodFactory() { if (this.messageHandlerMethodFactory == null) { this.messageHandlerMethodFactory = createDefaultAzureHandlerMethodFactory(); } return this.messageHandlerMethodFactory; } public void setMessageHandlerMethodFactory(MessageHandlerMethodFactory messageHandlerMethodFactory) { this.messageHandlerMethodFactory = messageHandlerMethodFactory; } private MessageHandlerMethodFactory createDefaultAzureHandlerMethodFactory() { DefaultMessageHandlerMethodFactory defaultFactory = new DefaultMessageHandlerMethodFactory(); if (beanFactory != null) { defaultFactory.setBeanFactory(beanFactory); } defaultFactory.afterPropertiesSet(); return defaultFactory; } } /** * Get the default bean name for an implementation class of {@link AzureListenerAnnotationBeanPostProcessorAdapter}. * @return the default bean name for the implementation class. */ public abstract String getDefaultAzureListenerAnnotationBeanPostProcessorBeanName(); }
class AzureListenerAnnotationBeanPostProcessorAdapter<T> implements MergedBeanDefinitionPostProcessor, Ordered, BeanFactoryAware, SmartInitializingSingleton { private static final Logger LOGGER = LoggerFactory.getLogger(AzureListenerAnnotationBeanPostProcessorAdapter.class); public static final String DEFAULT_AZURE_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME = "azureListenerEndpointRegistry"; /** * The bean name of the default {@link MessageListenerContainerFactory}. */ protected String containerFactoryBeanName; private final MessageHandlerMethodFactoryAdapter messageHandlerMethodFactory = new MessageHandlerMethodFactoryAdapter(); protected final AtomicInteger counter = new AtomicInteger(); private final Set<Class<?>> nonAnnotatedClasses = Collections.newSetFromMap(new ConcurrentHashMap<>(64)); private final AzureListenerEndpointRegistrar registrar = new AzureListenerEndpointRegistrar(); @Nullable private AzureListenerEndpointRegistry endpointRegistry; @Nullable private BeanFactory beanFactory; @Nullable private StringValueResolver embeddedValueResolver; /** * Set the container factory bean name. * @param containerFactoryBeanName the container factory bean name. */ public void setContainerFactoryBeanName(String containerFactoryBeanName) { this.containerFactoryBeanName = containerFactoryBeanName; } @Override public int getOrder() { return LOWEST_PRECEDENCE; } /** * Making a {@link BeanFactory} available is optional; if not set, * {@link AzureListenerConfigurer} beans won't get autodetected and an */ @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; if (beanFactory instanceof ConfigurableBeanFactory) { this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory); } this.registrar.setBeanFactory(beanFactory); } @Override public void afterSingletonsInstantiated() { this.nonAnnotatedClasses.clear(); if (this.beanFactory instanceof ListableBeanFactory) { Map<String, AzureListenerConfigurer> beans = ((ListableBeanFactory) this.beanFactory).getBeansOfType(AzureListenerConfigurer.class); List<AzureListenerConfigurer> configurers = new ArrayList<>(beans.values()); AnnotationAwareOrderComparator.sort(configurers); for (AzureListenerConfigurer configurer : configurers) { configurer.configureAzureListeners(this.registrar); } } if (this.containerFactoryBeanName != null) { this.registrar.setContainerFactoryBeanName(this.containerFactoryBeanName); } if (this.registrar.getEndpointRegistry() == null) { if (this.endpointRegistry == null) { Assert.state(this.beanFactory != null, "BeanFactory must be set to find endpoint registry by bean name"); this.endpointRegistry = this.beanFactory.getBean(DEFAULT_AZURE_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME, AzureListenerEndpointRegistry.class); } this.registrar.setEndpointRegistry(this.endpointRegistry); } MessageHandlerMethodFactory handlerMethodFactory = this.registrar.getMessageHandlerMethodFactory(); if (handlerMethodFactory != null) { this.messageHandlerMethodFactory.setMessageHandlerMethodFactory(handlerMethodFactory); } this.registrar.afterPropertiesSet(); } @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { } /** * @throws BeansException in case of errors */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * @throws BeansException in case of errors */ @Override /** * Process the given {@link T} annotation on the given method, * registering a corresponding endpoint for the given bean instance. * * @param listenerAnnotation the annotation to process * @param mostSpecificMethod the annotated method * @param bean the instance to invoke the method on * @see AzureListenerEndpointRegistrar * @throws BeanInitializationException If no ListenerContainerFactory could be found. */ private void processAzureListener(T listenerAnnotation, Method mostSpecificMethod, Object bean) { Method invocableMethod = AopUtils.selectInvocableMethod(mostSpecificMethod, bean.getClass()); AzureListenerEndpoint endpoint = createAndConfigureMethodListenerEndpoint(listenerAnnotation, bean, invocableMethod, beanFactory, messageHandlerMethodFactory); MessageListenerContainerFactory<?> factory = null; String containerFactoryBeanNameResolved = resolve(getContainerFactoryBeanName(listenerAnnotation)); if (StringUtils.hasText(containerFactoryBeanNameResolved)) { Assert.state(this.beanFactory != null, "BeanFactory must be set to obtain container factory by bean name"); try { factory = this.beanFactory.getBean(containerFactoryBeanNameResolved, MessageListenerContainerFactory.class); } catch (NoSuchBeanDefinitionException ex) { throw new BeanInitializationException( "Could not register Azure listener endpoint on [" + mostSpecificMethod + "], no " + MessageListenerContainerFactory.class.getSimpleName() + " with id '" + containerFactoryBeanNameResolved + "' was found in the application context", ex); } } this.registrar.registerEndpoint(endpoint, factory); } protected abstract Set<T> findListenerMethods(Method method); /** * Instantiate an empty {@link AzureListenerEndpoint} and perform further * configuration with provided parameters in {@link * * @param listenerAnnotation the listener annotation * @param bean the object instance that should manage this endpoint. * @param method the method to invoke to process a message managed by this endpoint. * @param beanFactory the Spring bean factory to use to resolve expressions * @param messageHandlerMethodFactory the {@link MessageHandlerMethodFactory} to use to build the * {@link InvocableHandlerMethod} responsible to manage the invocation of * this endpoint. * * @return an {@link AzureListenerEndpoint} implementation. */ protected abstract AzureListenerEndpoint createAndConfigureMethodListenerEndpoint( T listenerAnnotation, Object bean, Method method, BeanFactory beanFactory, MessageHandlerMethodFactory messageHandlerMethodFactory); protected abstract String getEndpointId(T listenerAnnotation); protected abstract String getContainerFactoryBeanName(T listenerAnnotation); protected abstract Class<T> getListenerType(); @Nullable protected String resolve(String value) { return (this.embeddedValueResolver != null ? this.embeddedValueResolver.resolveStringValue(value) : value); } /** * A {@link MessageHandlerMethodFactory} adapter that offers a configurable underlying * instance to use. Useful if the factory to use is determined once the endpoints * have been registered but not created yet. * * @see AzureListenerEndpointRegistrar */ private class MessageHandlerMethodFactoryAdapter implements MessageHandlerMethodFactory { @Nullable private MessageHandlerMethodFactory messageHandlerMethodFactory; @Override public InvocableHandlerMethod createInvocableHandlerMethod(Object bean, Method method) { return getMessageHandlerMethodFactory().createInvocableHandlerMethod(bean, method); } private MessageHandlerMethodFactory getMessageHandlerMethodFactory() { if (this.messageHandlerMethodFactory == null) { this.messageHandlerMethodFactory = createDefaultAzureHandlerMethodFactory(); } return this.messageHandlerMethodFactory; } public void setMessageHandlerMethodFactory(MessageHandlerMethodFactory messageHandlerMethodFactory) { this.messageHandlerMethodFactory = messageHandlerMethodFactory; } private MessageHandlerMethodFactory createDefaultAzureHandlerMethodFactory() { DefaultMessageHandlerMethodFactory defaultFactory = new DefaultMessageHandlerMethodFactory(); if (beanFactory != null) { defaultFactory.setBeanFactory(beanFactory); } defaultFactory.afterPropertiesSet(); return defaultFactory; } } /** * Get the default bean name for an implementation class of {@link AzureListenerAnnotationBeanPostProcessorAdapter}. * @return the default bean name for the implementation class. */ public abstract String getDefaultAzureListenerAnnotationBeanPostProcessorBeanName(); }
Yes, not needed
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AopInfrastructureBean || bean instanceof MessageListenerContainerFactory || bean instanceof AzureListenerEndpointRegistry) { return bean; } Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean); if (!this.nonAnnotatedClasses.contains(targetClass)) { Map<Method, Set<T>> annotatedMethods = MethodIntrospector.selectMethods(targetClass, (MethodIntrospector.MetadataLookup<Set<T>>) method -> { Set<T> listenerMethods = findListenerMethods(method); return (!listenerMethods.isEmpty() ? listenerMethods : null); }); if (annotatedMethods.isEmpty()) { this.nonAnnotatedClasses.add(targetClass); if (LOGGER.isTraceEnabled()) { LOGGER.trace("No @AzureMessageListener annotations found on bean type: {}", targetClass); } } else { annotatedMethods.forEach((method, listeners) -> listeners .forEach(listener -> processAzureListener(listener, method, bean))); if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} @AzureMessageListener methods processed on bean '{}': {}", annotatedMethods.size(), beanName, annotatedMethods); } } } return bean; }
if (LOGGER.isTraceEnabled()) {
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AopInfrastructureBean || bean instanceof MessageListenerContainerFactory || bean instanceof AzureListenerEndpointRegistry) { return bean; } Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean); if (!this.nonAnnotatedClasses.contains(targetClass)) { Map<Method, Set<T>> annotatedMethods = MethodIntrospector.selectMethods(targetClass, (MethodIntrospector.MetadataLookup<Set<T>>) method -> { Set<T> listenerMethods = findListenerMethods(method); return (!listenerMethods.isEmpty() ? listenerMethods : null); }); if (annotatedMethods.isEmpty()) { this.nonAnnotatedClasses.add(targetClass); LOGGER.trace("No @AzureMessageListener annotations found on bean type: {}", targetClass); } else { annotatedMethods.forEach((method, listeners) -> listeners .forEach(listener -> processAzureListener(listener, method, bean))); LOGGER.debug("{} @AzureMessageListener methods processed on bean '{}': {}", annotatedMethods.size(), beanName, annotatedMethods); } } return bean; }
class AzureListenerAnnotationBeanPostProcessorAdapter<T> implements MergedBeanDefinitionPostProcessor, Ordered, BeanFactoryAware, SmartInitializingSingleton { private static final Logger LOGGER = LoggerFactory.getLogger(AzureListenerAnnotationBeanPostProcessorAdapter.class); public static final String DEFAULT_AZURE_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME = "azureListenerEndpointRegistry"; /** * The bean name of the default {@link MessageListenerContainerFactory}. */ protected String containerFactoryBeanName; private final MessageHandlerMethodFactoryAdapter messageHandlerMethodFactory = new MessageHandlerMethodFactoryAdapter(); protected final AtomicInteger counter = new AtomicInteger(); private final Set<Class<?>> nonAnnotatedClasses = Collections.newSetFromMap(new ConcurrentHashMap<>(64)); private final AzureListenerEndpointRegistrar registrar = new AzureListenerEndpointRegistrar(); @Nullable private AzureListenerEndpointRegistry endpointRegistry; @Nullable private BeanFactory beanFactory; @Nullable private StringValueResolver embeddedValueResolver; /** * Set the container factory bean name. * @param containerFactoryBeanName the container factory bean name. */ public void setContainerFactoryBeanName(String containerFactoryBeanName) { this.containerFactoryBeanName = containerFactoryBeanName; } @Override public int getOrder() { return LOWEST_PRECEDENCE; } /** * Making a {@link BeanFactory} available is optional; if not set, * {@link AzureListenerConfigurer} beans won't get autodetected and an */ @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; if (beanFactory instanceof ConfigurableBeanFactory) { this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory); } this.registrar.setBeanFactory(beanFactory); } @Override public void afterSingletonsInstantiated() { this.nonAnnotatedClasses.clear(); if (this.beanFactory instanceof ListableBeanFactory) { Map<String, AzureListenerConfigurer> beans = ((ListableBeanFactory) this.beanFactory).getBeansOfType(AzureListenerConfigurer.class); List<AzureListenerConfigurer> configurers = new ArrayList<>(beans.values()); AnnotationAwareOrderComparator.sort(configurers); for (AzureListenerConfigurer configurer : configurers) { configurer.configureAzureListeners(this.registrar); } } if (this.containerFactoryBeanName != null) { this.registrar.setContainerFactoryBeanName(this.containerFactoryBeanName); } if (this.registrar.getEndpointRegistry() == null) { if (this.endpointRegistry == null) { Assert.state(this.beanFactory != null, "BeanFactory must be set to find endpoint registry by bean name"); this.endpointRegistry = this.beanFactory.getBean(DEFAULT_AZURE_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME, AzureListenerEndpointRegistry.class); } this.registrar.setEndpointRegistry(this.endpointRegistry); } MessageHandlerMethodFactory handlerMethodFactory = this.registrar.getMessageHandlerMethodFactory(); if (handlerMethodFactory != null) { this.messageHandlerMethodFactory.setMessageHandlerMethodFactory(handlerMethodFactory); } this.registrar.afterPropertiesSet(); } @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { } /** * @throws BeansException in case of errors */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * @throws BeansException in case of errors */ @Override /** * Process the given {@link T} annotation on the given method, * registering a corresponding endpoint for the given bean instance. * * @param listenerAnnotation the annotation to process * @param mostSpecificMethod the annotated method * @param bean the instance to invoke the method on * @see AzureListenerEndpointRegistrar * @throws BeanInitializationException If no ListenerContainerFactory could be found. */ private void processAzureListener(T listenerAnnotation, Method mostSpecificMethod, Object bean) { Method invocableMethod = AopUtils.selectInvocableMethod(mostSpecificMethod, bean.getClass()); AzureListenerEndpoint endpoint = createAndConfigureMethodListenerEndpoint(listenerAnnotation, bean, invocableMethod, beanFactory, messageHandlerMethodFactory); MessageListenerContainerFactory<?> factory = null; String containerFactoryBeanNameResolved = resolve(getContainerFactoryBeanName(listenerAnnotation)); if (StringUtils.hasText(containerFactoryBeanNameResolved)) { Assert.state(this.beanFactory != null, "BeanFactory must be set to obtain container factory by bean name"); try { factory = this.beanFactory.getBean(containerFactoryBeanNameResolved, MessageListenerContainerFactory.class); } catch (NoSuchBeanDefinitionException ex) { throw new BeanInitializationException( "Could not register Azure listener endpoint on [" + mostSpecificMethod + "], no " + MessageListenerContainerFactory.class.getSimpleName() + " with id '" + containerFactoryBeanNameResolved + "' was found in the application context", ex); } } this.registrar.registerEndpoint(endpoint, factory); } protected abstract Set<T> findListenerMethods(Method method); /** * Instantiate an empty {@link AzureListenerEndpoint} and perform further * configuration with provided parameters in {@link * * @param listenerAnnotation the listener annotation * @param bean the object instance that should manage this endpoint. * @param method the method to invoke to process a message managed by this endpoint. * @param beanFactory the Spring bean factory to use to resolve expressions * @param messageHandlerMethodFactory the {@link MessageHandlerMethodFactory} to use to build the * {@link InvocableHandlerMethod} responsible to manage the invocation of * this endpoint. * * @return an {@link AzureListenerEndpoint} implementation. */ protected abstract AzureListenerEndpoint createAndConfigureMethodListenerEndpoint( T listenerAnnotation, Object bean, Method method, BeanFactory beanFactory, MessageHandlerMethodFactory messageHandlerMethodFactory); protected abstract String getEndpointId(T listenerAnnotation); protected abstract String getContainerFactoryBeanName(T listenerAnnotation); protected abstract Class<T> getListenerType(); @Nullable protected String resolve(String value) { return (this.embeddedValueResolver != null ? this.embeddedValueResolver.resolveStringValue(value) : value); } /** * A {@link MessageHandlerMethodFactory} adapter that offers a configurable underlying * instance to use. Useful if the factory to use is determined once the endpoints * have been registered but not created yet. * * @see AzureListenerEndpointRegistrar */ private class MessageHandlerMethodFactoryAdapter implements MessageHandlerMethodFactory { @Nullable private MessageHandlerMethodFactory messageHandlerMethodFactory; @Override public InvocableHandlerMethod createInvocableHandlerMethod(Object bean, Method method) { return getMessageHandlerMethodFactory().createInvocableHandlerMethod(bean, method); } private MessageHandlerMethodFactory getMessageHandlerMethodFactory() { if (this.messageHandlerMethodFactory == null) { this.messageHandlerMethodFactory = createDefaultAzureHandlerMethodFactory(); } return this.messageHandlerMethodFactory; } public void setMessageHandlerMethodFactory(MessageHandlerMethodFactory messageHandlerMethodFactory) { this.messageHandlerMethodFactory = messageHandlerMethodFactory; } private MessageHandlerMethodFactory createDefaultAzureHandlerMethodFactory() { DefaultMessageHandlerMethodFactory defaultFactory = new DefaultMessageHandlerMethodFactory(); if (beanFactory != null) { defaultFactory.setBeanFactory(beanFactory); } defaultFactory.afterPropertiesSet(); return defaultFactory; } } /** * Get the default bean name for an implementation class of {@link AzureListenerAnnotationBeanPostProcessorAdapter}. * @return the default bean name for the implementation class. */ public abstract String getDefaultAzureListenerAnnotationBeanPostProcessorBeanName(); }
class AzureListenerAnnotationBeanPostProcessorAdapter<T> implements MergedBeanDefinitionPostProcessor, Ordered, BeanFactoryAware, SmartInitializingSingleton { private static final Logger LOGGER = LoggerFactory.getLogger(AzureListenerAnnotationBeanPostProcessorAdapter.class); public static final String DEFAULT_AZURE_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME = "azureListenerEndpointRegistry"; /** * The bean name of the default {@link MessageListenerContainerFactory}. */ protected String containerFactoryBeanName; private final MessageHandlerMethodFactoryAdapter messageHandlerMethodFactory = new MessageHandlerMethodFactoryAdapter(); protected final AtomicInteger counter = new AtomicInteger(); private final Set<Class<?>> nonAnnotatedClasses = Collections.newSetFromMap(new ConcurrentHashMap<>(64)); private final AzureListenerEndpointRegistrar registrar = new AzureListenerEndpointRegistrar(); @Nullable private AzureListenerEndpointRegistry endpointRegistry; @Nullable private BeanFactory beanFactory; @Nullable private StringValueResolver embeddedValueResolver; /** * Set the container factory bean name. * @param containerFactoryBeanName the container factory bean name. */ public void setContainerFactoryBeanName(String containerFactoryBeanName) { this.containerFactoryBeanName = containerFactoryBeanName; } @Override public int getOrder() { return LOWEST_PRECEDENCE; } /** * Making a {@link BeanFactory} available is optional; if not set, * {@link AzureListenerConfigurer} beans won't get autodetected and an */ @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; if (beanFactory instanceof ConfigurableBeanFactory) { this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory); } this.registrar.setBeanFactory(beanFactory); } @Override public void afterSingletonsInstantiated() { this.nonAnnotatedClasses.clear(); if (this.beanFactory instanceof ListableBeanFactory) { Map<String, AzureListenerConfigurer> beans = ((ListableBeanFactory) this.beanFactory).getBeansOfType(AzureListenerConfigurer.class); List<AzureListenerConfigurer> configurers = new ArrayList<>(beans.values()); AnnotationAwareOrderComparator.sort(configurers); for (AzureListenerConfigurer configurer : configurers) { configurer.configureAzureListeners(this.registrar); } } if (this.containerFactoryBeanName != null) { this.registrar.setContainerFactoryBeanName(this.containerFactoryBeanName); } if (this.registrar.getEndpointRegistry() == null) { if (this.endpointRegistry == null) { Assert.state(this.beanFactory != null, "BeanFactory must be set to find endpoint registry by bean name"); this.endpointRegistry = this.beanFactory.getBean(DEFAULT_AZURE_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME, AzureListenerEndpointRegistry.class); } this.registrar.setEndpointRegistry(this.endpointRegistry); } MessageHandlerMethodFactory handlerMethodFactory = this.registrar.getMessageHandlerMethodFactory(); if (handlerMethodFactory != null) { this.messageHandlerMethodFactory.setMessageHandlerMethodFactory(handlerMethodFactory); } this.registrar.afterPropertiesSet(); } @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { } /** * @throws BeansException in case of errors */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * @throws BeansException in case of errors */ @Override /** * Process the given {@link T} annotation on the given method, * registering a corresponding endpoint for the given bean instance. * * @param listenerAnnotation the annotation to process * @param mostSpecificMethod the annotated method * @param bean the instance to invoke the method on * @see AzureListenerEndpointRegistrar * @throws BeanInitializationException If no ListenerContainerFactory could be found. */ private void processAzureListener(T listenerAnnotation, Method mostSpecificMethod, Object bean) { Method invocableMethod = AopUtils.selectInvocableMethod(mostSpecificMethod, bean.getClass()); AzureListenerEndpoint endpoint = createAndConfigureMethodListenerEndpoint(listenerAnnotation, bean, invocableMethod, beanFactory, messageHandlerMethodFactory); MessageListenerContainerFactory<?> factory = null; String containerFactoryBeanNameResolved = resolve(getContainerFactoryBeanName(listenerAnnotation)); if (StringUtils.hasText(containerFactoryBeanNameResolved)) { Assert.state(this.beanFactory != null, "BeanFactory must be set to obtain container factory by bean name"); try { factory = this.beanFactory.getBean(containerFactoryBeanNameResolved, MessageListenerContainerFactory.class); } catch (NoSuchBeanDefinitionException ex) { throw new BeanInitializationException( "Could not register Azure listener endpoint on [" + mostSpecificMethod + "], no " + MessageListenerContainerFactory.class.getSimpleName() + " with id '" + containerFactoryBeanNameResolved + "' was found in the application context", ex); } } this.registrar.registerEndpoint(endpoint, factory); } protected abstract Set<T> findListenerMethods(Method method); /** * Instantiate an empty {@link AzureListenerEndpoint} and perform further * configuration with provided parameters in {@link * * @param listenerAnnotation the listener annotation * @param bean the object instance that should manage this endpoint. * @param method the method to invoke to process a message managed by this endpoint. * @param beanFactory the Spring bean factory to use to resolve expressions * @param messageHandlerMethodFactory the {@link MessageHandlerMethodFactory} to use to build the * {@link InvocableHandlerMethod} responsible to manage the invocation of * this endpoint. * * @return an {@link AzureListenerEndpoint} implementation. */ protected abstract AzureListenerEndpoint createAndConfigureMethodListenerEndpoint( T listenerAnnotation, Object bean, Method method, BeanFactory beanFactory, MessageHandlerMethodFactory messageHandlerMethodFactory); protected abstract String getEndpointId(T listenerAnnotation); protected abstract String getContainerFactoryBeanName(T listenerAnnotation); protected abstract Class<T> getListenerType(); @Nullable protected String resolve(String value) { return (this.embeddedValueResolver != null ? this.embeddedValueResolver.resolveStringValue(value) : value); } /** * A {@link MessageHandlerMethodFactory} adapter that offers a configurable underlying * instance to use. Useful if the factory to use is determined once the endpoints * have been registered but not created yet. * * @see AzureListenerEndpointRegistrar */ private class MessageHandlerMethodFactoryAdapter implements MessageHandlerMethodFactory { @Nullable private MessageHandlerMethodFactory messageHandlerMethodFactory; @Override public InvocableHandlerMethod createInvocableHandlerMethod(Object bean, Method method) { return getMessageHandlerMethodFactory().createInvocableHandlerMethod(bean, method); } private MessageHandlerMethodFactory getMessageHandlerMethodFactory() { if (this.messageHandlerMethodFactory == null) { this.messageHandlerMethodFactory = createDefaultAzureHandlerMethodFactory(); } return this.messageHandlerMethodFactory; } public void setMessageHandlerMethodFactory(MessageHandlerMethodFactory messageHandlerMethodFactory) { this.messageHandlerMethodFactory = messageHandlerMethodFactory; } private MessageHandlerMethodFactory createDefaultAzureHandlerMethodFactory() { DefaultMessageHandlerMethodFactory defaultFactory = new DefaultMessageHandlerMethodFactory(); if (beanFactory != null) { defaultFactory.setBeanFactory(beanFactory); } defaultFactory.afterPropertiesSet(); return defaultFactory; } } /** * Get the default bean name for an implementation class of {@link AzureListenerAnnotationBeanPostProcessorAdapter}. * @return the default bean name for the implementation class. */ public abstract String getDefaultAzureListenerAnnotationBeanPostProcessorBeanName(); }
should we return immediately here if `get` returns null?
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.defer(() -> { Map<String, String> challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); String authorizationUriString = challengeAttributes.get("authorization_uri"); final URI authorizationUri; try { authorizationUri = new URI(authorizationUriString); } catch (URISyntaxException e) { return Mono.just(false); } this.tenantId = authorizationUri.getPath().split("/")[1]; TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext) .then(Mono.just(true)); }); }
String authorizationUriString = challengeAttributes.get("authorization_uri");
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.defer(() -> { Map<String, String> challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); String authorizationUriString = challengeAttributes.get("authorization_uri"); final URI authorizationUri; try { authorizationUri = new URI(authorizationUriString); } catch (URISyntaxException e) { return Mono.just(false); } this.tenantId = authorizationUri.getPath().split("/")[1]; TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext) .then(Mono.just(true)); }); }
class TableBearerTokenChallengeAuthorizationPolicy extends BearerTokenAuthenticationPolicy { private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private String[] scopes; private String tenantId; private boolean enabledTenantDiscovery; /** * Creates a {@link TableBearerTokenChallengeAuthorizationPolicy}. * * @param credential The token credential to authenticate the request. */ public TableBearerTokenChallengeAuthorizationPolicy(TokenCredential credential, boolean enabledTenantDiscovery, String... scopes) { super(credential, scopes); this.scopes = scopes; this.enabledTenantDiscovery = enabledTenantDiscovery; } /** * Extracts attributes off the bearer challenge in the authentication header. * * @param authenticateHeader The authentication header containing the challenge. * @param authChallengePrefix The authentication challenge name. * * @return A challenge attributes map. */ private static Map<String, String> extractChallengeAttributes(String authenticateHeader, String authChallengePrefix) { if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { return Collections.emptyMap(); } authenticateHeader = authenticateHeader.toLowerCase(Locale.ROOT).replace(authChallengePrefix.toLowerCase(Locale.ROOT), ""); String[] attributes = authenticateHeader.split(", "); Map<String, String> attributeMap = new HashMap<>(); for (String pair : attributes) { String[] keyValue = pair.split("="); attributeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return attributeMap; } /** * Verifies whether a challenge is bearer or not. * * @param authenticateHeader The authentication header containing all the challenges. * @param authChallengePrefix The authentication challenge name. * * @return A boolean indicating if the challenge is a bearer challenge or not. */ private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { return (!CoreUtils.isNullOrEmpty(authenticateHeader) && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); } @Override public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { if (this.tenantId != null || !enabledTenantDiscovery) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext); } return Mono.empty(); }); } @Override }
class TableBearerTokenChallengeAuthorizationPolicy extends BearerTokenAuthenticationPolicy { private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private String[] scopes; private volatile String tenantId; private boolean enableTenantDiscovery; /** * Creates a {@link TableBearerTokenChallengeAuthorizationPolicy}. * * @param credential The token credential to authenticate the request. */ public TableBearerTokenChallengeAuthorizationPolicy(TokenCredential credential, boolean enableTenantDiscovery, String... scopes) { super(credential, scopes); this.scopes = scopes; this.enableTenantDiscovery = enableTenantDiscovery; } /** * Extracts attributes off the bearer challenge in the authentication header. * * @param authenticateHeader The authentication header containing the challenge. * @param authChallengePrefix The authentication challenge name. * * @return A challenge attributes map. */ private static Map<String, String> extractChallengeAttributes(String authenticateHeader, String authChallengePrefix) { if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { return Collections.emptyMap(); } authenticateHeader = authenticateHeader.toLowerCase(Locale.ROOT).replace(authChallengePrefix.toLowerCase(Locale.ROOT), ""); String[] attributes = authenticateHeader.split(" "); Map<String, String> attributeMap = new HashMap<>(); for (String pair : attributes) { String[] keyValue = pair.split("="); attributeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return attributeMap; } /** * Verifies whether a challenge is bearer or not. * * @param authenticateHeader The authentication header containing all the challenges. * @param authChallengePrefix The authentication challenge name. * * @return A boolean indicating if the challenge is a bearer challenge or not. */ private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { return (!CoreUtils.isNullOrEmpty(authenticateHeader) && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); } @Override public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { if (this.tenantId != null || !enableTenantDiscovery) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext); } return Mono.empty(); }); } @Override }
URI creation in the try/catch block takes care of that in the following lines, we could certainly do it earlier if `get` returns `null` but I wonder if it's even necessary.
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.defer(() -> { Map<String, String> challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); String authorizationUriString = challengeAttributes.get("authorization_uri"); final URI authorizationUri; try { authorizationUri = new URI(authorizationUriString); } catch (URISyntaxException e) { return Mono.just(false); } this.tenantId = authorizationUri.getPath().split("/")[1]; TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext) .then(Mono.just(true)); }); }
String authorizationUriString = challengeAttributes.get("authorization_uri");
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.defer(() -> { Map<String, String> challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); String authorizationUriString = challengeAttributes.get("authorization_uri"); final URI authorizationUri; try { authorizationUri = new URI(authorizationUriString); } catch (URISyntaxException e) { return Mono.just(false); } this.tenantId = authorizationUri.getPath().split("/")[1]; TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext) .then(Mono.just(true)); }); }
class TableBearerTokenChallengeAuthorizationPolicy extends BearerTokenAuthenticationPolicy { private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private String[] scopes; private String tenantId; private boolean enabledTenantDiscovery; /** * Creates a {@link TableBearerTokenChallengeAuthorizationPolicy}. * * @param credential The token credential to authenticate the request. */ public TableBearerTokenChallengeAuthorizationPolicy(TokenCredential credential, boolean enabledTenantDiscovery, String... scopes) { super(credential, scopes); this.scopes = scopes; this.enabledTenantDiscovery = enabledTenantDiscovery; } /** * Extracts attributes off the bearer challenge in the authentication header. * * @param authenticateHeader The authentication header containing the challenge. * @param authChallengePrefix The authentication challenge name. * * @return A challenge attributes map. */ private static Map<String, String> extractChallengeAttributes(String authenticateHeader, String authChallengePrefix) { if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { return Collections.emptyMap(); } authenticateHeader = authenticateHeader.toLowerCase(Locale.ROOT).replace(authChallengePrefix.toLowerCase(Locale.ROOT), ""); String[] attributes = authenticateHeader.split(", "); Map<String, String> attributeMap = new HashMap<>(); for (String pair : attributes) { String[] keyValue = pair.split("="); attributeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return attributeMap; } /** * Verifies whether a challenge is bearer or not. * * @param authenticateHeader The authentication header containing all the challenges. * @param authChallengePrefix The authentication challenge name. * * @return A boolean indicating if the challenge is a bearer challenge or not. */ private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { return (!CoreUtils.isNullOrEmpty(authenticateHeader) && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); } @Override public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { if (this.tenantId != null || !enabledTenantDiscovery) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext); } return Mono.empty(); }); } @Override }
class TableBearerTokenChallengeAuthorizationPolicy extends BearerTokenAuthenticationPolicy { private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private String[] scopes; private volatile String tenantId; private boolean enableTenantDiscovery; /** * Creates a {@link TableBearerTokenChallengeAuthorizationPolicy}. * * @param credential The token credential to authenticate the request. */ public TableBearerTokenChallengeAuthorizationPolicy(TokenCredential credential, boolean enableTenantDiscovery, String... scopes) { super(credential, scopes); this.scopes = scopes; this.enableTenantDiscovery = enableTenantDiscovery; } /** * Extracts attributes off the bearer challenge in the authentication header. * * @param authenticateHeader The authentication header containing the challenge. * @param authChallengePrefix The authentication challenge name. * * @return A challenge attributes map. */ private static Map<String, String> extractChallengeAttributes(String authenticateHeader, String authChallengePrefix) { if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { return Collections.emptyMap(); } authenticateHeader = authenticateHeader.toLowerCase(Locale.ROOT).replace(authChallengePrefix.toLowerCase(Locale.ROOT), ""); String[] attributes = authenticateHeader.split(" "); Map<String, String> attributeMap = new HashMap<>(); for (String pair : attributes) { String[] keyValue = pair.split("="); attributeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return attributeMap; } /** * Verifies whether a challenge is bearer or not. * * @param authenticateHeader The authentication header containing all the challenges. * @param authChallengePrefix The authentication challenge name. * * @return A boolean indicating if the challenge is a bearer challenge or not. */ private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { return (!CoreUtils.isNullOrEmpty(authenticateHeader) && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); } @Override public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { if (this.tenantId != null || !enableTenantDiscovery) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext); } return Mono.empty(); }); } @Override }
The challenge header may also contain `resource_uri` which can be used to build the correct auth scopes, are you planning to use it? In TS if the challenge header contains it we use it to build the scopes `resoruce_uri + "/.default"`
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.defer(() -> { Map<String, String> challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); String authorizationUriString = challengeAttributes.get("authorization_uri"); final URI authorizationUri; try { authorizationUri = new URI(authorizationUriString); } catch (URISyntaxException e) { return Mono.just(false); } this.tenantId = authorizationUri.getPath().split("/")[1]; TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext) .then(Mono.just(true)); }); }
String authorizationUriString = challengeAttributes.get("authorization_uri");
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.defer(() -> { Map<String, String> challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); String authorizationUriString = challengeAttributes.get("authorization_uri"); final URI authorizationUri; try { authorizationUri = new URI(authorizationUriString); } catch (URISyntaxException e) { return Mono.just(false); } this.tenantId = authorizationUri.getPath().split("/")[1]; TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext) .then(Mono.just(true)); }); }
class TableBearerTokenChallengeAuthorizationPolicy extends BearerTokenAuthenticationPolicy { private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private String[] scopes; private String tenantId; private boolean enabledTenantDiscovery; /** * Creates a {@link TableBearerTokenChallengeAuthorizationPolicy}. * * @param credential The token credential to authenticate the request. */ public TableBearerTokenChallengeAuthorizationPolicy(TokenCredential credential, boolean enabledTenantDiscovery, String... scopes) { super(credential, scopes); this.scopes = scopes; this.enabledTenantDiscovery = enabledTenantDiscovery; } /** * Extracts attributes off the bearer challenge in the authentication header. * * @param authenticateHeader The authentication header containing the challenge. * @param authChallengePrefix The authentication challenge name. * * @return A challenge attributes map. */ private static Map<String, String> extractChallengeAttributes(String authenticateHeader, String authChallengePrefix) { if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { return Collections.emptyMap(); } authenticateHeader = authenticateHeader.toLowerCase(Locale.ROOT).replace(authChallengePrefix.toLowerCase(Locale.ROOT), ""); String[] attributes = authenticateHeader.split(", "); Map<String, String> attributeMap = new HashMap<>(); for (String pair : attributes) { String[] keyValue = pair.split("="); attributeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return attributeMap; } /** * Verifies whether a challenge is bearer or not. * * @param authenticateHeader The authentication header containing all the challenges. * @param authChallengePrefix The authentication challenge name. * * @return A boolean indicating if the challenge is a bearer challenge or not. */ private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { return (!CoreUtils.isNullOrEmpty(authenticateHeader) && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); } @Override public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { if (this.tenantId != null || !enabledTenantDiscovery) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext); } return Mono.empty(); }); } @Override }
class TableBearerTokenChallengeAuthorizationPolicy extends BearerTokenAuthenticationPolicy { private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private String[] scopes; private volatile String tenantId; private boolean enableTenantDiscovery; /** * Creates a {@link TableBearerTokenChallengeAuthorizationPolicy}. * * @param credential The token credential to authenticate the request. */ public TableBearerTokenChallengeAuthorizationPolicy(TokenCredential credential, boolean enableTenantDiscovery, String... scopes) { super(credential, scopes); this.scopes = scopes; this.enableTenantDiscovery = enableTenantDiscovery; } /** * Extracts attributes off the bearer challenge in the authentication header. * * @param authenticateHeader The authentication header containing the challenge. * @param authChallengePrefix The authentication challenge name. * * @return A challenge attributes map. */ private static Map<String, String> extractChallengeAttributes(String authenticateHeader, String authChallengePrefix) { if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { return Collections.emptyMap(); } authenticateHeader = authenticateHeader.toLowerCase(Locale.ROOT).replace(authChallengePrefix.toLowerCase(Locale.ROOT), ""); String[] attributes = authenticateHeader.split(" "); Map<String, String> attributeMap = new HashMap<>(); for (String pair : attributes) { String[] keyValue = pair.split("="); attributeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return attributeMap; } /** * Verifies whether a challenge is bearer or not. * * @param authenticateHeader The authentication header containing all the challenges. * @param authChallengePrefix The authentication challenge name. * * @return A boolean indicating if the challenge is a bearer challenge or not. */ private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { return (!CoreUtils.isNullOrEmpty(authenticateHeader) && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); } @Override public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { if (this.tenantId != null || !enableTenantDiscovery) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext); } return Mono.empty(); }); } @Override }
We are using it in Key Vault for Java so I gave it a thought, however I saw .NET is not actively using `resource_uri` in favor of using a constant value for the scope, is there a particular reason we chose to do this @christothes?
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.defer(() -> { Map<String, String> challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); String authorizationUriString = challengeAttributes.get("authorization_uri"); final URI authorizationUri; try { authorizationUri = new URI(authorizationUriString); } catch (URISyntaxException e) { return Mono.just(false); } this.tenantId = authorizationUri.getPath().split("/")[1]; TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext) .then(Mono.just(true)); }); }
String authorizationUriString = challengeAttributes.get("authorization_uri");
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.defer(() -> { Map<String, String> challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); String authorizationUriString = challengeAttributes.get("authorization_uri"); final URI authorizationUri; try { authorizationUri = new URI(authorizationUriString); } catch (URISyntaxException e) { return Mono.just(false); } this.tenantId = authorizationUri.getPath().split("/")[1]; TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext) .then(Mono.just(true)); }); }
class TableBearerTokenChallengeAuthorizationPolicy extends BearerTokenAuthenticationPolicy { private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private String[] scopes; private String tenantId; private boolean enabledTenantDiscovery; /** * Creates a {@link TableBearerTokenChallengeAuthorizationPolicy}. * * @param credential The token credential to authenticate the request. */ public TableBearerTokenChallengeAuthorizationPolicy(TokenCredential credential, boolean enabledTenantDiscovery, String... scopes) { super(credential, scopes); this.scopes = scopes; this.enabledTenantDiscovery = enabledTenantDiscovery; } /** * Extracts attributes off the bearer challenge in the authentication header. * * @param authenticateHeader The authentication header containing the challenge. * @param authChallengePrefix The authentication challenge name. * * @return A challenge attributes map. */ private static Map<String, String> extractChallengeAttributes(String authenticateHeader, String authChallengePrefix) { if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { return Collections.emptyMap(); } authenticateHeader = authenticateHeader.toLowerCase(Locale.ROOT).replace(authChallengePrefix.toLowerCase(Locale.ROOT), ""); String[] attributes = authenticateHeader.split(", "); Map<String, String> attributeMap = new HashMap<>(); for (String pair : attributes) { String[] keyValue = pair.split("="); attributeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return attributeMap; } /** * Verifies whether a challenge is bearer or not. * * @param authenticateHeader The authentication header containing all the challenges. * @param authChallengePrefix The authentication challenge name. * * @return A boolean indicating if the challenge is a bearer challenge or not. */ private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { return (!CoreUtils.isNullOrEmpty(authenticateHeader) && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); } @Override public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { if (this.tenantId != null || !enabledTenantDiscovery) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext); } return Mono.empty(); }); } @Override }
class TableBearerTokenChallengeAuthorizationPolicy extends BearerTokenAuthenticationPolicy { private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private String[] scopes; private volatile String tenantId; private boolean enableTenantDiscovery; /** * Creates a {@link TableBearerTokenChallengeAuthorizationPolicy}. * * @param credential The token credential to authenticate the request. */ public TableBearerTokenChallengeAuthorizationPolicy(TokenCredential credential, boolean enableTenantDiscovery, String... scopes) { super(credential, scopes); this.scopes = scopes; this.enableTenantDiscovery = enableTenantDiscovery; } /** * Extracts attributes off the bearer challenge in the authentication header. * * @param authenticateHeader The authentication header containing the challenge. * @param authChallengePrefix The authentication challenge name. * * @return A challenge attributes map. */ private static Map<String, String> extractChallengeAttributes(String authenticateHeader, String authChallengePrefix) { if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { return Collections.emptyMap(); } authenticateHeader = authenticateHeader.toLowerCase(Locale.ROOT).replace(authChallengePrefix.toLowerCase(Locale.ROOT), ""); String[] attributes = authenticateHeader.split(" "); Map<String, String> attributeMap = new HashMap<>(); for (String pair : attributes) { String[] keyValue = pair.split("="); attributeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return attributeMap; } /** * Verifies whether a challenge is bearer or not. * * @param authenticateHeader The authentication header containing all the challenges. * @param authChallengePrefix The authentication challenge name. * * @return A boolean indicating if the challenge is a bearer challenge or not. */ private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { return (!CoreUtils.isNullOrEmpty(authenticateHeader) && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); } @Override public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { if (this.tenantId != null || !enableTenantDiscovery) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes(this.scopes) .setTenantId(this.tenantId); return setAuthorizationHeader(context, tokenRequestContext); } return Mono.empty(); }); } @Override }
Any reason for using this overload with offset and count over just `new String(byteBuffer.array())`?
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody() .map(byteBuffer -> { if (byteBuffer.hasArray()) { return bodyStringBuilder.append(new String(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining(), StandardCharsets.UTF_8)); } else { return bodyStringBuilder.append(new String(FluxUtil.byteBufferToArray(byteBuffer.duplicate()), StandardCharsets.UTF_8)); } }) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } }
byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining(),
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody() .map(byteBuffer -> { if (byteBuffer.hasArray()) { return bodyStringBuilder.append(new String(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining(), StandardCharsets.UTF_8)); } else { return bodyStringBuilder.append(new String(FluxUtil.byteBufferToArray(byteBuffer.duplicate()), StandardCharsets.UTF_8)); } }) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; } }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; } }
nit: maybe we should move `byteBufferToArray` helper method to `CoreUtils` instead of having it in `FluxUtil`.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody() .map(byteBuffer -> { if (byteBuffer.hasArray()) { return bodyStringBuilder.append(new String(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining(), StandardCharsets.UTF_8)); } else { return bodyStringBuilder.append(new String(FluxUtil.byteBufferToArray(byteBuffer.duplicate()), StandardCharsets.UTF_8)); } }) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } }
return bodyStringBuilder.append(new String(FluxUtil.byteBufferToArray(byteBuffer.duplicate()),
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody() .map(byteBuffer -> { if (byteBuffer.hasArray()) { return bodyStringBuilder.append(new String(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining(), StandardCharsets.UTF_8)); } else { return bodyStringBuilder.append(new String(FluxUtil.byteBufferToArray(byteBuffer.duplicate()), StandardCharsets.UTF_8)); } }) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; } }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; } }
The backing array may not be fully written, ex ```java byte[] bytes = new byte[1024]; bytes[0] = 42; ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 1); ``` In this `ByteBuffer` only the first byte has been written but `.array()` will return the entire 1KB array.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody() .map(byteBuffer -> { if (byteBuffer.hasArray()) { return bodyStringBuilder.append(new String(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining(), StandardCharsets.UTF_8)); } else { return bodyStringBuilder.append(new String(FluxUtil.byteBufferToArray(byteBuffer.duplicate()), StandardCharsets.UTF_8)); } }) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } }
byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining(),
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody() .map(byteBuffer -> { if (byteBuffer.hasArray()) { return bodyStringBuilder.append(new String(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining(), StandardCharsets.UTF_8)); } else { return bodyStringBuilder.append(new String(FluxUtil.byteBufferToArray(byteBuffer.duplicate()), StandardCharsets.UTF_8)); } }) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; } }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; } }
A stupid question, why start from `byteBuffer.position()`? Is it common that someone sets the position? And if someone did, do we intent to read the remaining or the whole?
public String toString() { if (transactionId.hasArray()) { return new String(transactionId.array(), transactionId.arrayOffset() + transactionId.position(), transactionId.remaining(), StandardCharsets.UTF_8); } else { return new String(FluxUtil.byteBufferToArray(transactionId.duplicate()), StandardCharsets.UTF_8); } }
transactionId.remaining(), StandardCharsets.UTF_8);
public String toString() { if (transactionId.hasArray()) { return new String(transactionId.array(), transactionId.arrayOffset() + transactionId.position(), transactionId.remaining(), StandardCharsets.UTF_8); } else { return new String(FluxUtil.byteBufferToArray(transactionId.duplicate()), StandardCharsets.UTF_8); } }
class AmqpTransaction { private final ByteBuffer transactionId; /** * Creates {@link AmqpTransaction} given {@code transactionId}. * * @param transactionId The id for this transaction. * * @throws NullPointerException if {@code transactionId} is null. */ public AmqpTransaction(ByteBuffer transactionId) { this.transactionId = Objects.requireNonNull(transactionId, "'transactionId' cannot be null."); } /** * Gets the id for this transaction. * * @return The id for this transaction. */ public ByteBuffer getTransactionId() { return transactionId; } /** * String representation of the transaction id. * * @return string representation of the transaction id. */ }
class AmqpTransaction { private final ByteBuffer transactionId; /** * Creates {@link AmqpTransaction} given {@code transactionId}. * * @param transactionId The id for this transaction. * * @throws NullPointerException if {@code transactionId} is null. */ public AmqpTransaction(ByteBuffer transactionId) { this.transactionId = Objects.requireNonNull(transactionId, "'transactionId' cannot be null."); } /** * Gets the id for this transaction. * * @return The id for this transaction. */ public ByteBuffer getTransactionId() { return transactionId; } /** * String representation of the transaction id. * * @return string representation of the transaction id. */ }
Not a stupid question at all 😃 While it is unknown how often an `arrayOffset` and/or `position` to be set in a passed `ByteBuffer` using them ensures we're only accessing what is still considered readable by the `ByteBuffer`. For example, I create a `ByteBuffer` with a 4096 byte array, and I know the array has special metadata in the first 128 bytes. So, I'll create a wrapping `ByteBuffer` offset by 128 bytes, so its effective reading range are the bytes [128, 4096). At this point the `toString` logic highlighted will be based on that range, `new String(byte[], 128, 4096-128, UTF_8)` (pardon any off-by-one errors as I'm free-handing this). But, let's say next that I know the range [128, 1024) is either junk data or something unrelated to the string, I'll make the new position 1024-128 as there is an offset of 128. Now, the `toString` becomes `new String(byte[], 128+896, 4096, UTF_8)`. For the second question, this is more difficult on whether the `ByteBuffer`'s position should be mutated, in this case I'd say no as `toString` is more a representation and may result in broken runtime behavior if `transactionId` is fully consumed by it. Also, when debugging, many IDEs will call `toString` when inspecting the object in the debug window, likely breaking debugging.
public String toString() { if (transactionId.hasArray()) { return new String(transactionId.array(), transactionId.arrayOffset() + transactionId.position(), transactionId.remaining(), StandardCharsets.UTF_8); } else { return new String(FluxUtil.byteBufferToArray(transactionId.duplicate()), StandardCharsets.UTF_8); } }
transactionId.remaining(), StandardCharsets.UTF_8);
public String toString() { if (transactionId.hasArray()) { return new String(transactionId.array(), transactionId.arrayOffset() + transactionId.position(), transactionId.remaining(), StandardCharsets.UTF_8); } else { return new String(FluxUtil.byteBufferToArray(transactionId.duplicate()), StandardCharsets.UTF_8); } }
class AmqpTransaction { private final ByteBuffer transactionId; /** * Creates {@link AmqpTransaction} given {@code transactionId}. * * @param transactionId The id for this transaction. * * @throws NullPointerException if {@code transactionId} is null. */ public AmqpTransaction(ByteBuffer transactionId) { this.transactionId = Objects.requireNonNull(transactionId, "'transactionId' cannot be null."); } /** * Gets the id for this transaction. * * @return The id for this transaction. */ public ByteBuffer getTransactionId() { return transactionId; } /** * String representation of the transaction id. * * @return string representation of the transaction id. */ }
class AmqpTransaction { private final ByteBuffer transactionId; /** * Creates {@link AmqpTransaction} given {@code transactionId}. * * @param transactionId The id for this transaction. * * @throws NullPointerException if {@code transactionId} is null. */ public AmqpTransaction(ByteBuffer transactionId) { this.transactionId = Objects.requireNonNull(transactionId, "'transactionId' cannot be null."); } /** * Gets the id for this transaction. * * @return The id for this transaction. */ public ByteBuffer getTransactionId() { return transactionId; } /** * String representation of the transaction id. * * @return string representation of the transaction id. */ }
Add javadoc
public EventData() { this.context = Context.NONE; this.annotatedMessage = EMPTY_MESSAGE; this.properties = annotatedMessage.getApplicationProperties(); this.systemProperties = new SystemProperties(); }
}
public EventData() { this.context = Context.NONE; this.annotatedMessage = EMPTY_MESSAGE; this.properties = annotatedMessage.getApplicationProperties(); this.systemProperties = new SystemProperties(); }
class EventData extends MessageContent { /* * These are properties owned by the service and set when a message is received. */ static final Set<String> RESERVED_SYSTEM_PROPERTIES; static final AmqpAnnotatedMessage EMPTY_MESSAGE = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(new byte[0])); private static final ClientLogger LOGGER = new ClientLogger(EventData.class); private final Map<String, Object> properties; private final SystemProperties systemProperties; private AmqpAnnotatedMessage annotatedMessage; private Context context; static { final Set<String> properties = new HashSet<>(); properties.add(OFFSET_ANNOTATION_NAME.getValue()); properties.add(PARTITION_KEY_ANNOTATION_NAME.getValue()); properties.add(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); properties.add(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); properties.add(PUBLISHER_ANNOTATION_NAME.getValue()); RESERVED_SYSTEM_PROPERTIES = Collections.unmodifiableSet(properties); } /** * Creates an event containing the {@code body}. * * @param body The data to set for this event. * * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(byte[] body) { this.context = Context.NONE; final AmqpMessageBody messageBody = AmqpMessageBody.fromData( Objects.requireNonNull(body, "'body' cannot be null.")); this.annotatedMessage = new AmqpAnnotatedMessage(messageBody); this.properties = annotatedMessage.getApplicationProperties(); this.systemProperties = new SystemProperties(); } /** * Creates an event containing the {@code body}. * * @param body The data to set for this event. * * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(ByteBuffer body) { this(Objects.requireNonNull(body, "'body' cannot be null.").array()); } /** * Creates an event by encoding the {@code body} using UTF-8 charset. * * @param body The string that will be UTF-8 encoded to create an event. * * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(String body) { this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(UTF_8)); } /** * Creates an event with the provided {@link BinaryData} as payload. * * @param body The {@link BinaryData} payload for this event. */ public EventData(BinaryData body) { this(Objects.requireNonNull(body, "'body' cannot be null.").toBytes()); } /** * Creates an event with the given {@code body}, system properties and context. Used in the case where a message * is received from the service. * * @param context A specified key-value pair of type {@link Context}. * @param amqpAnnotatedMessage Backing annotated message. * * @throws NullPointerException if {@code amqpAnnotatedMessage} or {@code context} is {@code null}. * @throws IllegalArgumentException if {@code amqpAnnotatedMessage}'s body type is unknown. */ EventData(AmqpAnnotatedMessage amqpAnnotatedMessage, SystemProperties systemProperties, Context context) { this.context = Objects.requireNonNull(context, "'context' cannot be null."); this.properties = Collections.unmodifiableMap(amqpAnnotatedMessage.getApplicationProperties()); this.annotatedMessage = Objects.requireNonNull(amqpAnnotatedMessage, "'amqpAnnotatedMessage' cannot be null."); this.systemProperties = systemProperties; switch (annotatedMessage.getBody().getBodyType()) { case DATA: break; case SEQUENCE: case VALUE: LOGGER.warning("Message body type '{}' is not supported in EH. " + " Getting contents of body may throw.", annotatedMessage.getBody().getBodyType()); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Body type not valid " + annotatedMessage.getBody().getBodyType())); } } /** * Gets the set of free-form event properties which may be used for passing metadata associated with the event with * the event body during Event Hubs operations. A common use-case for {@code properties()} is to associate * serialization hints for the {@link * * <p><strong>Adding serialization hint using {@code getProperties()}</strong></p> * <p>In the sample, the type of telemetry is indicated by adding an application property with key "eventType".</p> * * <!-- src_embed com.azure.messaging.eventhubs.eventdata.getProperties --> * <pre> * TelemetryEvent telemetry = new TelemetryEvent& * byte[] serializedTelemetryData = telemetry.toString& * * EventData eventData = new EventData& * eventData.getProperties& * </pre> * <!-- end com.azure.messaging.eventhubs.eventdata.getProperties --> * * @return Application properties associated with this {@link EventData}. For received {@link EventData}, the map is * a read-only view. */ public Map<String, Object> getProperties() { return properties; } /** * Properties that are populated by Event Hubs service. As these are populated by the Event Hubs service, they are * only present on a <b>received</b> {@link EventData}. Provides an abstraction on top of properties exposed by * {@link * {@link * * @return An encapsulation of all system properties appended by EventHubs service into {@link EventData}. If the * {@link EventData} is not received from the Event Hubs service, the values returned are {@code null}. */ public Map<String, Object> getSystemProperties() { return systemProperties; } /** * Gets the actual payload/data wrapped by EventData. * * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public byte[] getBody() { return annotatedMessage.getBody().getFirstData(); } /** * Returns event data as UTF-8 decoded string. * * @return UTF-8 decoded string representation of the event data. */ public String getBodyAsString() { return new String(annotatedMessage.getBody().getFirstData(), UTF_8); } /** * Returns the {@link BinaryData} payload associated with this event. * * @return the {@link BinaryData} payload associated with this event. */ @Override public BinaryData getBodyAsBinaryData() { return BinaryData.fromBytes(annotatedMessage.getBody().getFirstData()); } /** * {@inheritDoc} */ @Override public EventData setBodyAsBinaryData(BinaryData binaryData) { this.annotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(binaryData.toBytes())); return this; } /** * Gets the offset of the event when it was received from the associated Event Hub partition. This is only present * on a <b>received</b> {@link EventData}. * * @return The offset within the Event Hub partition of the received event. {@code null} if the {@link EventData} * was not received from Event Hubs service. */ public Long getOffset() { return systemProperties.getOffset(); } /** * Gets the partition hashing key if it was set when originally publishing the event. If it exists, this value was * used to compute a hash to select a partition to send the message to. This is only present on a <b>received</b> * {@link EventData}. * * @return A partition key for this Event Data. {@code null} if the {@link EventData} was not received from Event * Hubs service or there was no partition key set when the event was sent to the Event Hub. */ public String getPartitionKey() { return systemProperties.getPartitionKey(); } /** * Gets the instant, in UTC, of when the event was enqueued in the Event Hub partition. This is only present on a * <b>received</b> {@link EventData}. * * @return The instant, in UTC, this was enqueued in the Event Hub partition. {@code null} if the {@link EventData} * was not received from Event Hubs service. */ public Instant getEnqueuedTime() { return systemProperties.getEnqueuedTime(); } /** * Gets the sequence number assigned to the event when it was enqueued in the associated Event Hub partition. This * is unique for every message received in the Event Hub partition. This is only present on a <b>received</b> {@link * EventData}. * * @return The sequence number for this event. {@code null} if the {@link EventData} was not received from Event * Hubs service. */ public Long getSequenceNumber() { return systemProperties.getSequenceNumber(); } /** * Gets the underlying AMQP message. * * @return The underlying AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return annotatedMessage; } /** * Gets the content type. * * @return The content type. */ public String getContentType() { return annotatedMessage.getProperties().getContentType(); } /** * Sets the content type. * * @param contentType The content type. * * @return The updated {@link EventData}. */ public EventData setContentType(String contentType) { annotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets the correlation id. * * @return The correlation id. {@code null} if there is none set. */ public String getCorrelationId() { final AmqpMessageId messageId = annotatedMessage.getProperties().getCorrelationId(); return messageId != null ? messageId.toString() : null; } /** * Sets the correlation id. * * @param correlationId The correlation id. * * @return The updated {@link EventData}. */ public EventData setCorrelationId(String correlationId) { final AmqpMessageId id = correlationId != null ? new AmqpMessageId(correlationId) : null; annotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the message id. * * @return The message id. {@code null} if there is none set. */ public String getMessageId() { final AmqpMessageId messageId = annotatedMessage.getProperties().getMessageId(); return messageId != null ? messageId.toString() : null; } /** * Sets the message id. * * @param messageId The message id. * * @return The updated {@link EventData}. */ public EventData setMessageId(String messageId) { final AmqpMessageId id = messageId != null ? new AmqpMessageId(messageId) : null; annotatedMessage.getProperties().setMessageId(id); return this; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EventData eventData = (EventData) o; return Arrays.equals(annotatedMessage.getBody().getFirstData(), eventData.annotatedMessage.getBody().getFirstData()); } /** * {@inheritDoc} */ @Override public int hashCode() { return Arrays.hashCode(annotatedMessage.getBody().getFirstData()); } /** * A specified key-value pair of type {@link Context} to set additional information on the event. * * @return the {@link Context} object set on the event */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Event Data. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link EventData}. * * @throws NullPointerException if {@code key} or {@code value} is null. */ public EventData addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } }
class EventData extends MessageContent { /* * These are properties owned by the service and set when a message is received. */ static final Set<String> RESERVED_SYSTEM_PROPERTIES; static final AmqpAnnotatedMessage EMPTY_MESSAGE = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(new byte[0])); private static final ClientLogger LOGGER = new ClientLogger(EventData.class); private final Map<String, Object> properties; private final SystemProperties systemProperties; private AmqpAnnotatedMessage annotatedMessage; private Context context; static { final Set<String> properties = new HashSet<>(); properties.add(OFFSET_ANNOTATION_NAME.getValue()); properties.add(PARTITION_KEY_ANNOTATION_NAME.getValue()); properties.add(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); properties.add(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); properties.add(PUBLISHER_ANNOTATION_NAME.getValue()); RESERVED_SYSTEM_PROPERTIES = Collections.unmodifiableSet(properties); } /** * Creates an event with an empty body. */ /** * Creates an event containing the {@code body}. * * @param body The data to set for this event. * * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(byte[] body) { this.context = Context.NONE; final AmqpMessageBody messageBody = AmqpMessageBody.fromData( Objects.requireNonNull(body, "'body' cannot be null.")); this.annotatedMessage = new AmqpAnnotatedMessage(messageBody); this.properties = annotatedMessage.getApplicationProperties(); this.systemProperties = new SystemProperties(); } /** * Creates an event containing the {@code body}. * * @param body The data to set for this event. * * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(ByteBuffer body) { this(Objects.requireNonNull(body, "'body' cannot be null.").array()); } /** * Creates an event by encoding the {@code body} using UTF-8 charset. * * @param body The string that will be UTF-8 encoded to create an event. * * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(String body) { this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(UTF_8)); } /** * Creates an event with the provided {@link BinaryData} as payload. * * @param body The {@link BinaryData} payload for this event. */ public EventData(BinaryData body) { this(Objects.requireNonNull(body, "'body' cannot be null.").toBytes()); } /** * Creates an event with the given {@code body}, system properties and context. Used in the case where a message * is received from the service. * * @param context A specified key-value pair of type {@link Context}. * @param amqpAnnotatedMessage Backing annotated message. * * @throws NullPointerException if {@code amqpAnnotatedMessage} or {@code context} is {@code null}. * @throws IllegalArgumentException if {@code amqpAnnotatedMessage}'s body type is unknown. */ EventData(AmqpAnnotatedMessage amqpAnnotatedMessage, SystemProperties systemProperties, Context context) { this.context = Objects.requireNonNull(context, "'context' cannot be null."); this.properties = Collections.unmodifiableMap(amqpAnnotatedMessage.getApplicationProperties()); this.annotatedMessage = Objects.requireNonNull(amqpAnnotatedMessage, "'amqpAnnotatedMessage' cannot be null."); this.systemProperties = systemProperties; switch (annotatedMessage.getBody().getBodyType()) { case DATA: break; case SEQUENCE: case VALUE: LOGGER.warning("Message body type '{}' is not supported in EH. " + " Getting contents of body may throw.", annotatedMessage.getBody().getBodyType()); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Body type not valid " + annotatedMessage.getBody().getBodyType())); } } /** * Gets the set of free-form event properties which may be used for passing metadata associated with the event with * the event body during Event Hubs operations. A common use-case for {@code properties()} is to associate * serialization hints for the {@link * * <p><strong>Adding serialization hint using {@code getProperties()}</strong></p> * <p>In the sample, the type of telemetry is indicated by adding an application property with key "eventType".</p> * * <!-- src_embed com.azure.messaging.eventhubs.eventdata.getProperties --> * <pre> * TelemetryEvent telemetry = new TelemetryEvent& * byte[] serializedTelemetryData = telemetry.toString& * * EventData eventData = new EventData& * eventData.getProperties& * </pre> * <!-- end com.azure.messaging.eventhubs.eventdata.getProperties --> * * @return Application properties associated with this {@link EventData}. For received {@link EventData}, the map is * a read-only view. */ public Map<String, Object> getProperties() { return properties; } /** * Properties that are populated by Event Hubs service. As these are populated by the Event Hubs service, they are * only present on a <b>received</b> {@link EventData}. Provides an abstraction on top of properties exposed by * {@link * {@link * * @return An encapsulation of all system properties appended by EventHubs service into {@link EventData}. If the * {@link EventData} is not received from the Event Hubs service, the values returned are {@code null}. */ public Map<String, Object> getSystemProperties() { return systemProperties; } /** * Gets the actual payload/data wrapped by EventData. * * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public byte[] getBody() { return annotatedMessage.getBody().getFirstData(); } /** * Returns event data as UTF-8 decoded string. * * @return UTF-8 decoded string representation of the event data. */ public String getBodyAsString() { return new String(annotatedMessage.getBody().getFirstData(), UTF_8); } /** * Returns the {@link BinaryData} payload associated with this event. * * @return the {@link BinaryData} payload associated with this event. */ @Override public BinaryData getBodyAsBinaryData() { return BinaryData.fromBytes(annotatedMessage.getBody().getFirstData()); } /** * Sets a new binary body and corresponding {@link AmqpAnnotatedMessage} on the event. Contents from * {@link */ @Override public EventData setBodyAsBinaryData(BinaryData binaryData) { final AmqpAnnotatedMessage current = this.annotatedMessage; this.annotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(binaryData.toBytes())); if (current == null) { return this; } this.annotatedMessage.getApplicationProperties().putAll(current.getApplicationProperties()); this.annotatedMessage.getDeliveryAnnotations().putAll(current.getDeliveryAnnotations()); this.annotatedMessage.getFooter().putAll(current.getFooter()); this.annotatedMessage.getMessageAnnotations().putAll(current.getMessageAnnotations()); final AmqpMessageHeader header = this.annotatedMessage.getHeader(); header.setDeliveryCount(current.getHeader().getDeliveryCount()) .setDurable(current.getHeader().isDurable()) .setFirstAcquirer(current.getHeader().isFirstAcquirer()) .setPriority(current.getHeader().getPriority()) .setTimeToLive(current.getHeader().getTimeToLive()); final AmqpMessageProperties props = this.annotatedMessage.getProperties(); props.setAbsoluteExpiryTime(current.getProperties().getAbsoluteExpiryTime()) .setContentEncoding(current.getProperties().getContentEncoding()) .setContentType(current.getProperties().getContentType()) .setCorrelationId(current.getProperties().getCorrelationId()) .setCreationTime(current.getProperties().getCreationTime()) .setGroupId(current.getProperties().getGroupId()) .setGroupSequence(current.getProperties().getGroupSequence()) .setMessageId(current.getProperties().getMessageId()) .setReplyTo(current.getProperties().getReplyTo()) .setReplyToGroupId(current.getProperties().getReplyToGroupId()) .setSubject(current.getProperties().getSubject()) .setTo(current.getProperties().getTo()) .setUserId(current.getProperties().getUserId()); return this; } /** * Gets the offset of the event when it was received from the associated Event Hub partition. This is only present * on a <b>received</b> {@link EventData}. * * @return The offset within the Event Hub partition of the received event. {@code null} if the {@link EventData} * was not received from Event Hubs service. */ public Long getOffset() { return systemProperties.getOffset(); } /** * Gets the partition hashing key if it was set when originally publishing the event. If it exists, this value was * used to compute a hash to select a partition to send the message to. This is only present on a <b>received</b> * {@link EventData}. * * @return A partition key for this Event Data. {@code null} if the {@link EventData} was not received from Event * Hubs service or there was no partition key set when the event was sent to the Event Hub. */ public String getPartitionKey() { return systemProperties.getPartitionKey(); } /** * Gets the instant, in UTC, of when the event was enqueued in the Event Hub partition. This is only present on a * <b>received</b> {@link EventData}. * * @return The instant, in UTC, this was enqueued in the Event Hub partition. {@code null} if the {@link EventData} * was not received from Event Hubs service. */ public Instant getEnqueuedTime() { return systemProperties.getEnqueuedTime(); } /** * Gets the sequence number assigned to the event when it was enqueued in the associated Event Hub partition. This * is unique for every message received in the Event Hub partition. This is only present on a <b>received</b> {@link * EventData}. * * @return The sequence number for this event. {@code null} if the {@link EventData} was not received from Event * Hubs service. */ public Long getSequenceNumber() { return systemProperties.getSequenceNumber(); } /** * Gets the underlying AMQP message. * * @return The underlying AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return annotatedMessage; } /** * Gets the content type. * * @return The content type. */ public String getContentType() { return annotatedMessage.getProperties().getContentType(); } /** * Sets the content type. * * @param contentType The content type. * * @return The updated {@link EventData}. */ public EventData setContentType(String contentType) { annotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets the correlation id. * * @return The correlation id. {@code null} if there is none set. */ public String getCorrelationId() { final AmqpMessageId messageId = annotatedMessage.getProperties().getCorrelationId(); return messageId != null ? messageId.toString() : null; } /** * Sets the correlation id. * * @param correlationId The correlation id. * * @return The updated {@link EventData}. */ public EventData setCorrelationId(String correlationId) { final AmqpMessageId id = correlationId != null ? new AmqpMessageId(correlationId) : null; annotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the message id. * * @return The message id. {@code null} if there is none set. */ public String getMessageId() { final AmqpMessageId messageId = annotatedMessage.getProperties().getMessageId(); return messageId != null ? messageId.toString() : null; } /** * Sets the message id. * * @param messageId The message id. * * @return The updated {@link EventData}. */ public EventData setMessageId(String messageId) { final AmqpMessageId id = messageId != null ? new AmqpMessageId(messageId) : null; annotatedMessage.getProperties().setMessageId(id); return this; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EventData eventData = (EventData) o; return Arrays.equals(annotatedMessage.getBody().getFirstData(), eventData.annotatedMessage.getBody().getFirstData()); } /** * {@inheritDoc} */ @Override public int hashCode() { return Arrays.hashCode(annotatedMessage.getBody().getFirstData()); } /** * A specified key-value pair of type {@link Context} to set additional information on the event. * * @return the {@link Context} object set on the event */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Event Data. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link EventData}. * * @throws NullPointerException if {@code key} or {@code value} is null. */ public EventData addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } }
yes, I'll make a change.
public void onNext(ByteBuf bytes) { try { if (isWriting) { onError(new IllegalStateException("Received onNext while processing another write operation.")); } else { bytes = bytes.retain(); write(bytes, bytes.nioBuffer()); } } catch (Throwable throwable) { bytes.release(); onError(throwable); } }
bytes.release();
public void onNext(ByteBuf bytes) { try { bytes = bytes.retain(); if (isWriting) { onError(new IllegalStateException("Received onNext while processing another write operation.")); } else { write(bytes, bytes.nioBuffer()); } } catch (Throwable throwable) { bytes.release(); onError(throwable); } }
class NettyFileWriteSubscriber implements Subscriber<ByteBuf> { private volatile boolean isWriting = false; private volatile boolean isCompleted = false; private static final ClientLogger LOGGER = new ClientLogger(NettyFileWriteSubscriber.class); private final AsynchronousFileChannel fileChannel; private final AtomicLong position; private final MonoSink<Void> emitter; private Subscription subscription; public NettyFileWriteSubscriber(AsynchronousFileChannel fileChannel, long position, MonoSink<Void> emitter) { this.fileChannel = fileChannel; this.position = new AtomicLong(position); this.emitter = emitter; } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.subscription, s)) { subscription = s; s.request(1); } } @Override private void write(ByteBuf nettyBytes, ByteBuffer nioBytes) { isWriting = true; fileChannel.write(nioBytes, position.get(), nettyBytes, new CompletionHandler<Integer, ByteBuf>() { @Override public void completed(Integer result, ByteBuf attachment) { position.addAndGet(result); if (nioBytes.hasRemaining()) { write(nettyBytes, nioBytes); } else { nettyBytes.release(); isWriting = false; if (isCompleted) { emitter.success(); } else { subscription.request(1); } } } @Override public void failed(Throwable exc, ByteBuf attachment) { attachment.release(); onError(exc); } }); } @Override public void onError(Throwable throwable) { isWriting = false; subscription.cancel(); emitter.error(LOGGER.logThrowableAsError(throwable)); } @Override public void onComplete() { isCompleted = true; if (!isWriting) { emitter.success(); } } }
class NettyFileWriteSubscriber implements Subscriber<ByteBuf> { private volatile boolean isWriting = false; private volatile boolean isCompleted = false; private static final ClientLogger LOGGER = new ClientLogger(NettyFileWriteSubscriber.class); private final AsynchronousFileChannel fileChannel; private final AtomicLong position; private final MonoSink<Void> emitter; private Subscription subscription; public NettyFileWriteSubscriber(AsynchronousFileChannel fileChannel, long position, MonoSink<Void> emitter) { this.fileChannel = fileChannel; this.position = new AtomicLong(position); this.emitter = emitter; } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.subscription, s)) { subscription = s; s.request(1); } } @Override private void write(ByteBuf nettyBytes, ByteBuffer nioBytes) { isWriting = true; fileChannel.write(nioBytes, position.get(), nettyBytes, new CompletionHandler<Integer, ByteBuf>() { @Override public void completed(Integer result, ByteBuf attachment) { position.addAndGet(result); if (nioBytes.hasRemaining()) { write(nettyBytes, nioBytes); } else { nettyBytes.release(); isWriting = false; if (isCompleted) { emitter.success(); } else { subscription.request(1); } } } @Override public void failed(Throwable exc, ByteBuf attachment) { attachment.release(); onError(exc); } }); } @Override public void onError(Throwable throwable) { isWriting = false; subscription.cancel(); emitter.error(LOGGER.logThrowableAsError(throwable)); } @Override public void onComplete() { isCompleted = true; if (!isWriting) { emitter.success(); } } }
Would the time required to "delete" the file after each download count towards the perf test op/s metrics?
public Mono<Void> runAsync() { File file = new File(tempDir, UUID.randomUUID().toString()); return blobAsyncClient.downloadToFile(file.getAbsolutePath()) .doFinally(ignored -> { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } }) .then(); }
if (!file.delete()){
public Mono<Void> runAsync() { File file = new File(tempDir, UUID.randomUUID().toString()); return blobAsyncClient.downloadToFile(file.getAbsolutePath()) .doFinally(ignored -> { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } }) .then(); }
class DownloadBlobToFileTest extends ContainerTest<PerfStressOptions> { private final BlobClient blobClient; private final BlobAsyncClient blobAsyncClient; private final File tempDir; public DownloadBlobToFileTest(PerfStressOptions options) { super(options); String blobName = "downloadToFileTest"; blobClient = blobContainerClient.getBlobClient(blobName); blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient(blobName); try { tempDir = Files.createTempDirectory("downloadToFileTest").toFile(); tempDir.deleteOnExit(); } catch (IOException e) { throw new UncheckedIOException(e); } } public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(blobAsyncClient.upload(createRandomByteBufferFlux(options.getSize()), null)) .then(); } @Override public void run() { File file = new File(tempDir, UUID.randomUUID().toString()); try { blobClient.downloadToFile(file.getAbsolutePath()); } finally { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } } } @Override }
class DownloadBlobToFileTest extends ContainerTest<PerfStressOptions> { private final BlobClient blobClient; private final BlobAsyncClient blobAsyncClient; private final File tempDir; public DownloadBlobToFileTest(PerfStressOptions options) { super(options); String blobName = "downloadToFileTest"; blobClient = blobContainerClient.getBlobClient(blobName); blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient(blobName); try { tempDir = Files.createTempDirectory("downloadToFileTest").toFile(); tempDir.deleteOnExit(); } catch (IOException e) { throw new UncheckedIOException(e); } } public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(blobAsyncClient.upload(createRandomByteBufferFlux(options.getSize()), null)) .then(); } @Override public void run() { File file = new File(tempDir, UUID.randomUUID().toString()); try { blobClient.downloadToFile(file.getAbsolutePath()); } finally { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } } } @Override }
Yes. This will be ~constant component of results (relatively small though, it's just node removal from fs tree). So we'd be comparing (new_perf + const) against (old_perf + const). The alternative of generating garbage and cleaning it up at the end (even with dir cleanup instead of shutdown hook per file) isn't great - for long running benchmarks with larger data size this might not scale well and eat up whole disk at some point.
public Mono<Void> runAsync() { File file = new File(tempDir, UUID.randomUUID().toString()); return blobAsyncClient.downloadToFile(file.getAbsolutePath()) .doFinally(ignored -> { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } }) .then(); }
if (!file.delete()){
public Mono<Void> runAsync() { File file = new File(tempDir, UUID.randomUUID().toString()); return blobAsyncClient.downloadToFile(file.getAbsolutePath()) .doFinally(ignored -> { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } }) .then(); }
class DownloadBlobToFileTest extends ContainerTest<PerfStressOptions> { private final BlobClient blobClient; private final BlobAsyncClient blobAsyncClient; private final File tempDir; public DownloadBlobToFileTest(PerfStressOptions options) { super(options); String blobName = "downloadToFileTest"; blobClient = blobContainerClient.getBlobClient(blobName); blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient(blobName); try { tempDir = Files.createTempDirectory("downloadToFileTest").toFile(); tempDir.deleteOnExit(); } catch (IOException e) { throw new UncheckedIOException(e); } } public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(blobAsyncClient.upload(createRandomByteBufferFlux(options.getSize()), null)) .then(); } @Override public void run() { File file = new File(tempDir, UUID.randomUUID().toString()); try { blobClient.downloadToFile(file.getAbsolutePath()); } finally { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } } } @Override }
class DownloadBlobToFileTest extends ContainerTest<PerfStressOptions> { private final BlobClient blobClient; private final BlobAsyncClient blobAsyncClient; private final File tempDir; public DownloadBlobToFileTest(PerfStressOptions options) { super(options); String blobName = "downloadToFileTest"; blobClient = blobContainerClient.getBlobClient(blobName); blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient(blobName); try { tempDir = Files.createTempDirectory("downloadToFileTest").toFile(); tempDir.deleteOnExit(); } catch (IOException e) { throw new UncheckedIOException(e); } } public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(blobAsyncClient.upload(createRandomByteBufferFlux(options.getSize()), null)) .then(); } @Override public void run() { File file = new File(tempDir, UUID.randomUUID().toString()); try { blobClient.downloadToFile(file.getAbsolutePath()); } finally { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } } } @Override }
FWIW, some of the benchmarks that I'm running are expected to generate ~300GB of garbage files for this scenario.
public Mono<Void> runAsync() { File file = new File(tempDir, UUID.randomUUID().toString()); return blobAsyncClient.downloadToFile(file.getAbsolutePath()) .doFinally(ignored -> { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } }) .then(); }
if (!file.delete()){
public Mono<Void> runAsync() { File file = new File(tempDir, UUID.randomUUID().toString()); return blobAsyncClient.downloadToFile(file.getAbsolutePath()) .doFinally(ignored -> { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } }) .then(); }
class DownloadBlobToFileTest extends ContainerTest<PerfStressOptions> { private final BlobClient blobClient; private final BlobAsyncClient blobAsyncClient; private final File tempDir; public DownloadBlobToFileTest(PerfStressOptions options) { super(options); String blobName = "downloadToFileTest"; blobClient = blobContainerClient.getBlobClient(blobName); blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient(blobName); try { tempDir = Files.createTempDirectory("downloadToFileTest").toFile(); tempDir.deleteOnExit(); } catch (IOException e) { throw new UncheckedIOException(e); } } public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(blobAsyncClient.upload(createRandomByteBufferFlux(options.getSize()), null)) .then(); } @Override public void run() { File file = new File(tempDir, UUID.randomUUID().toString()); try { blobClient.downloadToFile(file.getAbsolutePath()); } finally { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } } } @Override }
class DownloadBlobToFileTest extends ContainerTest<PerfStressOptions> { private final BlobClient blobClient; private final BlobAsyncClient blobAsyncClient; private final File tempDir; public DownloadBlobToFileTest(PerfStressOptions options) { super(options); String blobName = "downloadToFileTest"; blobClient = blobContainerClient.getBlobClient(blobName); blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient(blobName); try { tempDir = Files.createTempDirectory("downloadToFileTest").toFile(); tempDir.deleteOnExit(); } catch (IOException e) { throw new UncheckedIOException(e); } } public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(blobAsyncClient.upload(createRandomByteBufferFlux(options.getSize()), null)) .then(); } @Override public void run() { File file = new File(tempDir, UUID.randomUUID().toString()); try { blobClient.downloadToFile(file.getAbsolutePath()); } finally { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } } } @Override }
Yeah, delete operations are generally quick and may not change the perf numbers by a huge margin. However, we should consider having a `beforeRun()` and `afterRun()` methods in the perf framework that run before and after `runAsync()`/`run()` methods to allow for "setup-startTimer-runPerfTest-stopTimer-cleanup". cc: @g2vinay
public Mono<Void> runAsync() { File file = new File(tempDir, UUID.randomUUID().toString()); return blobAsyncClient.downloadToFile(file.getAbsolutePath()) .doFinally(ignored -> { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } }) .then(); }
if (!file.delete()){
public Mono<Void> runAsync() { File file = new File(tempDir, UUID.randomUUID().toString()); return blobAsyncClient.downloadToFile(file.getAbsolutePath()) .doFinally(ignored -> { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } }) .then(); }
class DownloadBlobToFileTest extends ContainerTest<PerfStressOptions> { private final BlobClient blobClient; private final BlobAsyncClient blobAsyncClient; private final File tempDir; public DownloadBlobToFileTest(PerfStressOptions options) { super(options); String blobName = "downloadToFileTest"; blobClient = blobContainerClient.getBlobClient(blobName); blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient(blobName); try { tempDir = Files.createTempDirectory("downloadToFileTest").toFile(); tempDir.deleteOnExit(); } catch (IOException e) { throw new UncheckedIOException(e); } } public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(blobAsyncClient.upload(createRandomByteBufferFlux(options.getSize()), null)) .then(); } @Override public void run() { File file = new File(tempDir, UUID.randomUUID().toString()); try { blobClient.downloadToFile(file.getAbsolutePath()); } finally { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } } } @Override }
class DownloadBlobToFileTest extends ContainerTest<PerfStressOptions> { private final BlobClient blobClient; private final BlobAsyncClient blobAsyncClient; private final File tempDir; public DownloadBlobToFileTest(PerfStressOptions options) { super(options); String blobName = "downloadToFileTest"; blobClient = blobContainerClient.getBlobClient(blobName); blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient(blobName); try { tempDir = Files.createTempDirectory("downloadToFileTest").toFile(); tempDir.deleteOnExit(); } catch (IOException e) { throw new UncheckedIOException(e); } } public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(blobAsyncClient.upload(createRandomByteBufferFlux(options.getSize()), null)) .then(); } @Override public void run() { File file = new File(tempDir, UUID.randomUUID().toString()); try { blobClient.downloadToFile(file.getAbsolutePath()); } finally { if (!file.delete()){ throw new IllegalStateException("Unable to delete test file"); } } } @Override }
NIT: shouldn't that extra space be reverted?
protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = new ConcurrentHashMap<>(); if (responseHeaders != null) { for (Map.Entry<String, String> entry : responseHeaders.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { this.responseHeaders.put(entry.getKey(), entry.getValue()); } } } }
for (Map.Entry<String, String> entry : responseHeaders.entrySet()) {
protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = new ConcurrentHashMap<>(); if (responseHeaders != null) { for (Map.Entry<String, String> entry: responseHeaders.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { this.responseHeaders.put(entry.getKey(), entry.getValue()); } } } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private static final ObjectMapper mapper = new ObjectMapper(); private final static String USER_AGENT = Utils.getUserAgent(); /** * Status code */ private final int statusCode; /** * Response headers */ private final Map<String, String> responseHeaders; /** * Cosmos diagnostics */ private CosmosDiagnostics cosmosDiagnostics; /** * Request timeline */ private RequestTimeline requestTimeline; /** * Channel acquisition timeline */ private RntbdChannelAcquisitionTimeline channelAcquisitionTimeline; /** * Cosmos error */ private CosmosError cosmosError; /** * RNTBD channel task queue size */ private int rntbdChannelTaskQueueSize; /** * RNTBD endpoint statistics */ private RntbdEndpointStatistics rntbdEndpointStatistics; /** * LSN */ long lsn; /** * Partition key range ID */ String partitionKeyRangeId; /** * Request headers */ Map<String, String> requestHeaders; /** * Request URI */ Uri requestUri; /** * Resource address */ String resourceAddress; /** * Request payload length */ private int requestPayloadLength; /** * RNTBD pending request queue size */ private int rntbdPendingRequestQueueSize; /** * RNTBD request length */ private int rntbdRequestLength; /** * RNTBD response length */ private int rntbdResponseLength; /** * Sending request has started */ private boolean sendingRequestHasStarted; /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param message the string message. * @param responseHeaders the response headers. * @param cause the inner exception */ /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { try { ObjectNode messageNode = mapper.createObjectNode(); messageNode.put("innerErrorMessage", innerErrorMessage()); if (cosmosDiagnostics != null) { cosmosDiagnostics.fillCosmosDiagnostics(messageNode, null); } return mapper.writeValueAsString(messageNode); } catch (JsonProcessingException e) { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } /** * Gets the request charge as request units (RU) consumed by the operation. * <p> * For more information about the RU and factors that can impact the effective charges please visit * <a href="https: * * @return the request charge. */ public double getRequestCharge() { String value = this.getResponseHeaders().get(HttpConstants.HttpHeaders.REQUEST_CHARGE); if (StringUtils.isEmpty(value)) { return 0; } return Double.parseDouble(value); } @Override public String toString() { try { ObjectNode exceptionMessageNode = mapper.createObjectNode(); exceptionMessageNode.put("ClassName", getClass().getSimpleName()); exceptionMessageNode.put(USER_AGENT_KEY, USER_AGENT); exceptionMessageNode.put("statusCode", statusCode); exceptionMessageNode.put("resourceAddress", resourceAddress); if (cosmosError != null) { exceptionMessageNode.put("error", cosmosError.toJson()); } exceptionMessageNode.put("innerErrorMessage", innerErrorMessage()); exceptionMessageNode.put("causeInfo", causeInfo()); if (responseHeaders != null) { exceptionMessageNode.put("responseHeaders", responseHeaders.toString()); } List<Map.Entry<String, String>> filterRequestHeaders = filterSensitiveData(requestHeaders); if (filterRequestHeaders != null) { exceptionMessageNode.put("requestHeaders", filterRequestHeaders.toString()); } if(this.cosmosDiagnostics != null) { cosmosDiagnostics.fillCosmosDiagnostics(exceptionMessageNode, null); } return mapper.writeValueAsString(exceptionMessageNode); } catch (JsonProcessingException ex) { return getClass().getSimpleName() + "{" + USER_AGENT_KEY +"=" + USER_AGENT + ", error=" + cosmosError + ", " + "resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; } } String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } RntbdChannelAcquisitionTimeline getChannelAcquisitionTimeline() { return this.channelAcquisitionTimeline; } void setChannelAcquisitionTimeline(RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { this.channelAcquisitionTimeline = channelAcquisitionTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } static { ImplementationBridgeHelpers.CosmosExceptionHelper.setCosmosExceptionAccessor( new ImplementationBridgeHelpers.CosmosExceptionHelper.CosmosExceptionAccessor() { @Override public CosmosException createCosmosException(int statusCode, Exception innerException) { return new CosmosException(statusCode, innerException); } }); } }
class CosmosException extends AzureException { private static final long MAX_RETRY_AFTER_IN_MS = BatchExecUtils.MAX_RETRY_AFTER_IN_MS; private static final long serialVersionUID = 1L; private static final ObjectMapper mapper = new ObjectMapper(); private final static String USER_AGENT = Utils.getUserAgent(); /** * Status code */ private final int statusCode; /** * Response headers */ private final Map<String, String> responseHeaders; /** * Cosmos diagnostics */ private CosmosDiagnostics cosmosDiagnostics; /** * Request timeline */ private RequestTimeline requestTimeline; /** * Channel acquisition timeline */ private RntbdChannelAcquisitionTimeline channelAcquisitionTimeline; /** * Cosmos error */ private CosmosError cosmosError; /** * RNTBD channel task queue size */ private int rntbdChannelTaskQueueSize; /** * RNTBD endpoint statistics */ private RntbdEndpointStatistics rntbdEndpointStatistics; /** * LSN */ long lsn; /** * Partition key range ID */ String partitionKeyRangeId; /** * Request headers */ Map<String, String> requestHeaders; /** * Request URI */ Uri requestUri; /** * Resource address */ String resourceAddress; /** * Request payload length */ private int requestPayloadLength; /** * RNTBD pending request queue size */ private int rntbdPendingRequestQueueSize; /** * RNTBD request length */ private int rntbdRequestLength; /** * RNTBD response length */ private int rntbdResponseLength; /** * Sending request has started */ private boolean sendingRequestHasStarted; /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param message the string message. * @param responseHeaders the response headers. * @param cause the inner exception */ /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { try { ObjectNode messageNode = mapper.createObjectNode(); messageNode.put("innerErrorMessage", innerErrorMessage()); if (cosmosDiagnostics != null) { cosmosDiagnostics.fillCosmosDiagnostics(messageNode, null); } return mapper.writeValueAsString(messageNode); } catch (JsonProcessingException e) { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Math.min(Long.parseLong(header), MAX_RETRY_AFTER_IN_MS); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } /** * Gets the request charge as request units (RU) consumed by the operation. * <p> * For more information about the RU and factors that can impact the effective charges please visit * <a href="https: * * @return the request charge. */ public double getRequestCharge() { String value = this.getResponseHeaders().get(HttpConstants.HttpHeaders.REQUEST_CHARGE); if (StringUtils.isEmpty(value)) { return 0; } return Double.parseDouble(value); } @Override public String toString() { try { ObjectNode exceptionMessageNode = mapper.createObjectNode(); exceptionMessageNode.put("ClassName", getClass().getSimpleName()); exceptionMessageNode.put(USER_AGENT_KEY, USER_AGENT); exceptionMessageNode.put("statusCode", statusCode); exceptionMessageNode.put("resourceAddress", resourceAddress); if (cosmosError != null) { exceptionMessageNode.put("error", cosmosError.toJson()); } exceptionMessageNode.put("innerErrorMessage", innerErrorMessage()); exceptionMessageNode.put("causeInfo", causeInfo()); if (responseHeaders != null) { exceptionMessageNode.put("responseHeaders", responseHeaders.toString()); } List<Map.Entry<String, String>> filterRequestHeaders = filterSensitiveData(requestHeaders); if (filterRequestHeaders != null) { exceptionMessageNode.put("requestHeaders", filterRequestHeaders.toString()); } if(this.cosmosDiagnostics != null) { cosmosDiagnostics.fillCosmosDiagnostics(exceptionMessageNode, null); } return mapper.writeValueAsString(exceptionMessageNode); } catch (JsonProcessingException ex) { return getClass().getSimpleName() + "{" + USER_AGENT_KEY +"=" + USER_AGENT + ", error=" + cosmosError + ", " + "resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; } } String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } RntbdChannelAcquisitionTimeline getChannelAcquisitionTimeline() { return this.channelAcquisitionTimeline; } void setChannelAcquisitionTimeline(RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { this.channelAcquisitionTimeline = channelAcquisitionTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } static { ImplementationBridgeHelpers.CosmosExceptionHelper.setCosmosExceptionAccessor( new ImplementationBridgeHelpers.CosmosExceptionHelper.CosmosExceptionAccessor() { @Override public CosmosException createCosmosException(int statusCode, Exception innerException) { return new CosmosException(statusCode, innerException); } }); } }
This is different behavior from the constructor that takes a string input. I guess the constructor throws an exception and we should have the same behavior here.
static DateTimeRfc1123 fromString(final String date) { if (CoreUtils.isNullOrEmpty(date)) { return null; } return new DateTimeRfc1123(date); }
}
static DateTimeRfc1123 fromString(final String date) { if (CoreUtils.isNullOrEmpty(date)) { return null; } return new DateTimeRfc1123(date); }
class DateTimeRfc1123 { private static final ClientLogger LOGGER = new ClientLogger(DateTimeRfc1123.class); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); } /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * JSON creator for DateTimeRfc1123. * <p> * If {@code date} is null or an empty string null will be returned. * * @param date RFC1123 datetime string. * @return The DateTimeRfc1123 representation of the datetime string, or null if {@code date} is null or empty. */ @JsonCreator /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. * * @throws DateTimeException If the processing character is not a digit character. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static OffsetDateTime parse(final String date) { try { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } catch (DateTimeException | IllegalArgumentException | IndexOutOfBoundsException e) { return OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME); } } /** * Parses the specified substring of datetime to a 'int' value. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive. * @param endIndex The ending index, exclusive. * @return The specified substring. * * @throws DateTimeException If the processing character is not digit character. */ private static int parseInt(final CharSequence date, final int beginIndex, final int endIndex) { int num = 0; for (int i = beginIndex; i < endIndex; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw LOGGER.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } /** * Parses the specified month substring of date time to a number value, '1' represents the month of January, * '12' represents the month of December. * * @param date The date time string in RFC1123 format. * @param beginIndex The beginning index, inclusive, to the * @return The number value which represents the month of year. '1' represents the month of January, * '12' represents the month of December. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static int parseMonth(final CharSequence date, final int beginIndex) { switch (date.charAt(beginIndex)) { case 'J': switch (date.charAt(beginIndex + 1)) { case 'a': return 1; case 'u': switch (date.charAt(beginIndex + 2)) { case 'n': return 6; case 'l': return 7; default: throw LOGGER.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(beginIndex + 2)) { case 'r': return 3; case 'y': return 5; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(beginIndex + 2)) { case 'r': return 4; case 'g': return 8; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } /** * Convert the {@link OffsetDateTime dateTime} to date time string in RFC1123 format. * * @param dateTime The date time in OffsetDateTime format. * @return The date time string in RFC1123 format. * @throws IllegalArgumentException If {@link OffsetDateTime * {@link OffsetDateTime */ public static String toRfc1123String(OffsetDateTime dateTime) { dateTime = dateTime.withOffsetSameInstant(ZoneOffset.UTC); StringBuilder sb = new StringBuilder(32); final DayOfWeek dayOfWeek = dateTime.getDayOfWeek(); switch (dayOfWeek) { case MONDAY: sb.append("Mon, "); break; case TUESDAY: sb.append("Tue, "); break; case WEDNESDAY: sb.append("Wed, "); break; case THURSDAY: sb.append("Thu, "); break; case FRIDAY: sb.append("Fri, "); break; case SATURDAY: sb.append("Sat, "); break; case SUNDAY: sb.append("Sun, "); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown day of week " + dayOfWeek)); } zeroPad(dateTime.getDayOfMonth(), sb); final Month month = dateTime.getMonth(); switch (month) { case JANUARY: sb.append(" Jan "); break; case FEBRUARY: sb.append(" Feb "); break; case MARCH: sb.append(" Mar "); break; case APRIL: sb.append(" Apr "); break; case MAY: sb.append(" May "); break; case JUNE: sb.append(" Jun "); break; case JULY: sb.append(" Jul "); break; case AUGUST: sb.append(" Aug "); break; case SEPTEMBER: sb.append(" Sep "); break; case OCTOBER: sb.append(" Oct "); break; case NOVEMBER: sb.append(" Nov "); break; case DECEMBER: sb.append(" Dec "); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + month)); } sb.append(dateTime.getYear()); sb.append(" "); zeroPad(dateTime.getHour(), sb); sb.append(":"); zeroPad(dateTime.getMinute(), sb); sb.append(":"); zeroPad(dateTime.getSecond(), sb); sb.append(" GMT"); return sb.toString(); } private static void zeroPad(int value, StringBuilder sb) { if (value < 10) { sb.append("0"); } sb.append(value); } @Override public String toString() { return toRfc1123String(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
class DateTimeRfc1123 { private static final ClientLogger LOGGER = new ClientLogger(DateTimeRfc1123.class); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); } /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * JSON creator for DateTimeRfc1123. * <p> * If {@code date} is null or an empty string null will be returned. * * @param date RFC1123 datetime string. * @return The DateTimeRfc1123 representation of the datetime string, or null if {@code date} is null or empty. */ @JsonCreator /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. * * @throws DateTimeException If the processing character is not a digit character. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static OffsetDateTime parse(final String date) { try { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } catch (DateTimeException | IllegalArgumentException | IndexOutOfBoundsException e) { return OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME); } } /** * Parses the specified substring of datetime to a 'int' value. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive. * @param endIndex The ending index, exclusive. * @return The specified substring. * * @throws DateTimeException If the processing character is not digit character. */ private static int parseInt(final CharSequence date, final int beginIndex, final int endIndex) { int num = 0; for (int i = beginIndex; i < endIndex; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw LOGGER.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } /** * Parses the specified month substring of date time to a number value, '1' represents the month of January, * '12' represents the month of December. * * @param date The date time string in RFC1123 format. * @param beginIndex The beginning index, inclusive, to the * @return The number value which represents the month of year. '1' represents the month of January, * '12' represents the month of December. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static int parseMonth(final CharSequence date, final int beginIndex) { switch (date.charAt(beginIndex)) { case 'J': switch (date.charAt(beginIndex + 1)) { case 'a': return 1; case 'u': switch (date.charAt(beginIndex + 2)) { case 'n': return 6; case 'l': return 7; default: throw LOGGER.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(beginIndex + 2)) { case 'r': return 3; case 'y': return 5; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(beginIndex + 2)) { case 'r': return 4; case 'g': return 8; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } /** * Convert the {@link OffsetDateTime dateTime} to date time string in RFC1123 format. * * @param dateTime The date time in OffsetDateTime format. * @return The date time string in RFC1123 format. * @throws IllegalArgumentException If {@link OffsetDateTime * {@link OffsetDateTime */ public static String toRfc1123String(OffsetDateTime dateTime) { dateTime = dateTime.withOffsetSameInstant(ZoneOffset.UTC); StringBuilder sb = new StringBuilder(32); final DayOfWeek dayOfWeek = dateTime.getDayOfWeek(); switch (dayOfWeek) { case MONDAY: sb.append("Mon, "); break; case TUESDAY: sb.append("Tue, "); break; case WEDNESDAY: sb.append("Wed, "); break; case THURSDAY: sb.append("Thu, "); break; case FRIDAY: sb.append("Fri, "); break; case SATURDAY: sb.append("Sat, "); break; case SUNDAY: sb.append("Sun, "); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown day of week " + dayOfWeek)); } zeroPad(dateTime.getDayOfMonth(), sb); final Month month = dateTime.getMonth(); switch (month) { case JANUARY: sb.append(" Jan "); break; case FEBRUARY: sb.append(" Feb "); break; case MARCH: sb.append(" Mar "); break; case APRIL: sb.append(" Apr "); break; case MAY: sb.append(" May "); break; case JUNE: sb.append(" Jun "); break; case JULY: sb.append(" Jul "); break; case AUGUST: sb.append(" Aug "); break; case SEPTEMBER: sb.append(" Sep "); break; case OCTOBER: sb.append(" Oct "); break; case NOVEMBER: sb.append(" Nov "); break; case DECEMBER: sb.append(" Dec "); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + month)); } sb.append(dateTime.getYear()); sb.append(" "); zeroPad(dateTime.getHour(), sb); sb.append(":"); zeroPad(dateTime.getMinute(), sb); sb.append(":"); zeroPad(dateTime.getSecond(), sb); sb.append(" GMT"); return sb.toString(); } private static void zeroPad(int value, StringBuilder sb) { if (value < 10) { sb.append("0"); } sb.append(value); } @Override public String toString() { return toRfc1123String(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
That is correct that the behavior is different, in most cases empty string won't appear in the constructor given JSON handling is a bit better than XML (where `<XmlProperty></XmlProperty>` may be handled differently than `<XmlProperty/>`). Without this change the XmlMapper itself would need to have coercion configuration changes for DateTimeRfc1123 to treat empty string as null. I think this change is more appropriate than having a coercion and matches the pattern we've seen more often with models in `azure-core` with JsonCreators.
static DateTimeRfc1123 fromString(final String date) { if (CoreUtils.isNullOrEmpty(date)) { return null; } return new DateTimeRfc1123(date); }
}
static DateTimeRfc1123 fromString(final String date) { if (CoreUtils.isNullOrEmpty(date)) { return null; } return new DateTimeRfc1123(date); }
class DateTimeRfc1123 { private static final ClientLogger LOGGER = new ClientLogger(DateTimeRfc1123.class); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); } /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * JSON creator for DateTimeRfc1123. * <p> * If {@code date} is null or an empty string null will be returned. * * @param date RFC1123 datetime string. * @return The DateTimeRfc1123 representation of the datetime string, or null if {@code date} is null or empty. */ @JsonCreator /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. * * @throws DateTimeException If the processing character is not a digit character. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static OffsetDateTime parse(final String date) { try { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } catch (DateTimeException | IllegalArgumentException | IndexOutOfBoundsException e) { return OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME); } } /** * Parses the specified substring of datetime to a 'int' value. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive. * @param endIndex The ending index, exclusive. * @return The specified substring. * * @throws DateTimeException If the processing character is not digit character. */ private static int parseInt(final CharSequence date, final int beginIndex, final int endIndex) { int num = 0; for (int i = beginIndex; i < endIndex; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw LOGGER.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } /** * Parses the specified month substring of date time to a number value, '1' represents the month of January, * '12' represents the month of December. * * @param date The date time string in RFC1123 format. * @param beginIndex The beginning index, inclusive, to the * @return The number value which represents the month of year. '1' represents the month of January, * '12' represents the month of December. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static int parseMonth(final CharSequence date, final int beginIndex) { switch (date.charAt(beginIndex)) { case 'J': switch (date.charAt(beginIndex + 1)) { case 'a': return 1; case 'u': switch (date.charAt(beginIndex + 2)) { case 'n': return 6; case 'l': return 7; default: throw LOGGER.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(beginIndex + 2)) { case 'r': return 3; case 'y': return 5; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(beginIndex + 2)) { case 'r': return 4; case 'g': return 8; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } /** * Convert the {@link OffsetDateTime dateTime} to date time string in RFC1123 format. * * @param dateTime The date time in OffsetDateTime format. * @return The date time string in RFC1123 format. * @throws IllegalArgumentException If {@link OffsetDateTime * {@link OffsetDateTime */ public static String toRfc1123String(OffsetDateTime dateTime) { dateTime = dateTime.withOffsetSameInstant(ZoneOffset.UTC); StringBuilder sb = new StringBuilder(32); final DayOfWeek dayOfWeek = dateTime.getDayOfWeek(); switch (dayOfWeek) { case MONDAY: sb.append("Mon, "); break; case TUESDAY: sb.append("Tue, "); break; case WEDNESDAY: sb.append("Wed, "); break; case THURSDAY: sb.append("Thu, "); break; case FRIDAY: sb.append("Fri, "); break; case SATURDAY: sb.append("Sat, "); break; case SUNDAY: sb.append("Sun, "); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown day of week " + dayOfWeek)); } zeroPad(dateTime.getDayOfMonth(), sb); final Month month = dateTime.getMonth(); switch (month) { case JANUARY: sb.append(" Jan "); break; case FEBRUARY: sb.append(" Feb "); break; case MARCH: sb.append(" Mar "); break; case APRIL: sb.append(" Apr "); break; case MAY: sb.append(" May "); break; case JUNE: sb.append(" Jun "); break; case JULY: sb.append(" Jul "); break; case AUGUST: sb.append(" Aug "); break; case SEPTEMBER: sb.append(" Sep "); break; case OCTOBER: sb.append(" Oct "); break; case NOVEMBER: sb.append(" Nov "); break; case DECEMBER: sb.append(" Dec "); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + month)); } sb.append(dateTime.getYear()); sb.append(" "); zeroPad(dateTime.getHour(), sb); sb.append(":"); zeroPad(dateTime.getMinute(), sb); sb.append(":"); zeroPad(dateTime.getSecond(), sb); sb.append(" GMT"); return sb.toString(); } private static void zeroPad(int value, StringBuilder sb) { if (value < 10) { sb.append("0"); } sb.append(value); } @Override public String toString() { return toRfc1123String(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
class DateTimeRfc1123 { private static final ClientLogger LOGGER = new ClientLogger(DateTimeRfc1123.class); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); } /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * JSON creator for DateTimeRfc1123. * <p> * If {@code date} is null or an empty string null will be returned. * * @param date RFC1123 datetime string. * @return The DateTimeRfc1123 representation of the datetime string, or null if {@code date} is null or empty. */ @JsonCreator /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. * * @throws DateTimeException If the processing character is not a digit character. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static OffsetDateTime parse(final String date) { try { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } catch (DateTimeException | IllegalArgumentException | IndexOutOfBoundsException e) { return OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME); } } /** * Parses the specified substring of datetime to a 'int' value. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive. * @param endIndex The ending index, exclusive. * @return The specified substring. * * @throws DateTimeException If the processing character is not digit character. */ private static int parseInt(final CharSequence date, final int beginIndex, final int endIndex) { int num = 0; for (int i = beginIndex; i < endIndex; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw LOGGER.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } /** * Parses the specified month substring of date time to a number value, '1' represents the month of January, * '12' represents the month of December. * * @param date The date time string in RFC1123 format. * @param beginIndex The beginning index, inclusive, to the * @return The number value which represents the month of year. '1' represents the month of January, * '12' represents the month of December. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static int parseMonth(final CharSequence date, final int beginIndex) { switch (date.charAt(beginIndex)) { case 'J': switch (date.charAt(beginIndex + 1)) { case 'a': return 1; case 'u': switch (date.charAt(beginIndex + 2)) { case 'n': return 6; case 'l': return 7; default: throw LOGGER.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(beginIndex + 2)) { case 'r': return 3; case 'y': return 5; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(beginIndex + 2)) { case 'r': return 4; case 'g': return 8; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } /** * Convert the {@link OffsetDateTime dateTime} to date time string in RFC1123 format. * * @param dateTime The date time in OffsetDateTime format. * @return The date time string in RFC1123 format. * @throws IllegalArgumentException If {@link OffsetDateTime * {@link OffsetDateTime */ public static String toRfc1123String(OffsetDateTime dateTime) { dateTime = dateTime.withOffsetSameInstant(ZoneOffset.UTC); StringBuilder sb = new StringBuilder(32); final DayOfWeek dayOfWeek = dateTime.getDayOfWeek(); switch (dayOfWeek) { case MONDAY: sb.append("Mon, "); break; case TUESDAY: sb.append("Tue, "); break; case WEDNESDAY: sb.append("Wed, "); break; case THURSDAY: sb.append("Thu, "); break; case FRIDAY: sb.append("Fri, "); break; case SATURDAY: sb.append("Sat, "); break; case SUNDAY: sb.append("Sun, "); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown day of week " + dayOfWeek)); } zeroPad(dateTime.getDayOfMonth(), sb); final Month month = dateTime.getMonth(); switch (month) { case JANUARY: sb.append(" Jan "); break; case FEBRUARY: sb.append(" Feb "); break; case MARCH: sb.append(" Mar "); break; case APRIL: sb.append(" Apr "); break; case MAY: sb.append(" May "); break; case JUNE: sb.append(" Jun "); break; case JULY: sb.append(" Jul "); break; case AUGUST: sb.append(" Aug "); break; case SEPTEMBER: sb.append(" Sep "); break; case OCTOBER: sb.append(" Oct "); break; case NOVEMBER: sb.append(" Nov "); break; case DECEMBER: sb.append(" Dec "); break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + month)); } sb.append(dateTime.getYear()); sb.append(" "); zeroPad(dateTime.getHour(), sb); sb.append(":"); zeroPad(dateTime.getMinute(), sb); sb.append(":"); zeroPad(dateTime.getSecond(), sb); sb.append(" GMT"); return sb.toString(); } private static void zeroPad(int value, StringBuilder sb) { if (value < 10) { sb.append("0"); } sb.append(value); } @Override public String toString() { return toRfc1123String(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
Is it possible to reach this catch block before `retain`ing the `ByteBuf`?
public void onNext(ByteBuf bytes) { try { if (isWriting) { onError(new IllegalStateException("Received onNext while processing another write operation.")); } else { bytes = bytes.retain(); write(bytes, bytes.nioBuffer()); } } catch (Throwable throwable) { bytes.release(); onError(throwable); } }
bytes.release();
public void onNext(ByteBuf bytes) { try { bytes = bytes.retain(); if (isWriting) { onError(new IllegalStateException("Received onNext while processing another write operation.")); } else { write(bytes, bytes.nioBuffer()); } } catch (Throwable throwable) { bytes.release(); onError(throwable); } }
class NettyFileWriteSubscriber implements Subscriber<ByteBuf> { private volatile boolean isWriting = false; private volatile boolean isCompleted = false; private static final ClientLogger LOGGER = new ClientLogger(NettyFileWriteSubscriber.class); private final AsynchronousFileChannel fileChannel; private final AtomicLong position; private final MonoSink<Void> emitter; private Subscription subscription; public NettyFileWriteSubscriber(AsynchronousFileChannel fileChannel, long position, MonoSink<Void> emitter) { this.fileChannel = fileChannel; this.position = new AtomicLong(position); this.emitter = emitter; } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.subscription, s)) { subscription = s; s.request(1); } } @Override private void write(ByteBuf nettyBytes, ByteBuffer nioBytes) { isWriting = true; fileChannel.write(nioBytes, position.get(), nettyBytes, new CompletionHandler<Integer, ByteBuf>() { @Override public void completed(Integer result, ByteBuf attachment) { position.addAndGet(result); if (nioBytes.hasRemaining()) { write(nettyBytes, nioBytes); } else { nettyBytes.release(); isWriting = false; if (isCompleted) { emitter.success(); } else { subscription.request(1); } } } @Override public void failed(Throwable exc, ByteBuf attachment) { attachment.release(); onError(exc); } }); } @Override public void onError(Throwable throwable) { isWriting = false; subscription.cancel(); emitter.error(LOGGER.logThrowableAsError(throwable)); } @Override public void onComplete() { isCompleted = true; if (!isWriting) { emitter.success(); } } }
class NettyFileWriteSubscriber implements Subscriber<ByteBuf> { private volatile boolean isWriting = false; private volatile boolean isCompleted = false; private static final ClientLogger LOGGER = new ClientLogger(NettyFileWriteSubscriber.class); private final AsynchronousFileChannel fileChannel; private final AtomicLong position; private final MonoSink<Void> emitter; private Subscription subscription; public NettyFileWriteSubscriber(AsynchronousFileChannel fileChannel, long position, MonoSink<Void> emitter) { this.fileChannel = fileChannel; this.position = new AtomicLong(position); this.emitter = emitter; } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.subscription, s)) { subscription = s; s.request(1); } } @Override private void write(ByteBuf nettyBytes, ByteBuffer nioBytes) { isWriting = true; fileChannel.write(nioBytes, position.get(), nettyBytes, new CompletionHandler<Integer, ByteBuf>() { @Override public void completed(Integer result, ByteBuf attachment) { position.addAndGet(result); if (nioBytes.hasRemaining()) { write(nettyBytes, nioBytes); } else { nettyBytes.release(); isWriting = false; if (isCompleted) { emitter.success(); } else { subscription.request(1); } } } @Override public void failed(Throwable exc, ByteBuf attachment) { attachment.release(); onError(exc); } }); } @Override public void onError(Throwable throwable) { isWriting = false; subscription.cancel(); emitter.error(LOGGER.logThrowableAsError(throwable)); } @Override public void onComplete() { isCompleted = true; if (!isWriting) { emitter.success(); } } }
is `serviceRegistry.id()` guaranteed not null?
public boolean hasServiceRegistryBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry == null) { return false; } return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); }
&& serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID));
public boolean hasServiceRegistryBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry == null) { return false; } return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); }
class SpringAppImpl extends ExternalChildResourceImpl<SpringApp, AppResourceInner, SpringServiceImpl, SpringService> implements SpringApp, SpringApp.Definition, SpringApp.Update { private Creatable<SpringAppDeployment> springAppDeploymentToCreate = null; private final SpringAppDeploymentsImpl deployments = new SpringAppDeploymentsImpl(this); private final SpringAppServiceBindingsImpl serviceBindings = new SpringAppServiceBindingsImpl(this); private final SpringAppDomainsImpl domains = new SpringAppDomainsImpl(this); private FunctionalTaskItem setActiveDeploymentTask = null; SpringAppImpl(String name, SpringServiceImpl parent, AppResourceInner innerObject) { super(name, parent, innerObject); } @Override public boolean isPublic() { if (innerModel().properties() == null) { return false; } return innerModel().properties().publicProperty(); } @Override public boolean isHttpsOnly() { if (innerModel().properties() == null) { return false; } return innerModel().properties().httpsOnly(); } @Override public String url() { if (innerModel().properties() == null) { return null; } return innerModel().properties().url(); } @Override public String fqdn() { if (innerModel().properties() == null) { return null; } return innerModel().properties().fqdn(); } @Override public TemporaryDisk temporaryDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().temporaryDisk(); } @Override public PersistentDisk persistentDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().persistentDisk(); } @Override public ManagedIdentityProperties identity() { return innerModel().identity(); } @Override public String activeDeploymentName() { Optional<SpringAppDeployment> deployment = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); return deployment.map(SpringAppDeployment::appName).orElse(null); } @Override public SpringAppDeployment getActiveDeployment() { return getActiveDeploymentAsync().block(); } @Override public Mono<SpringAppDeployment> getActiveDeploymentAsync() { return deployments.listAsync().filter(SpringAppDeployment::isActive).singleOrEmpty(); } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithCreate<T>> SpringAppDeployments<T> deployments() { return (SpringAppDeployments<T>) deployments; } @Override public SpringAppServiceBindings serviceBindings() { return serviceBindings; } @Override public SpringAppDomains customDomains() { return domains; } @Override public Mono<ResourceUploadDefinition> getResourceUploadUrlAsync() { return manager().serviceClient().getApps().getResourceUploadUrlAsync( parent().resourceGroupName(), parent().name(), name()); } @Override public ResourceUploadDefinition getResourceUploadUrl() { return getResourceUploadUrlAsync().block(); } private void ensureProperty() { if (innerModel().properties() == null) { innerModel().withProperties(new AppResourceProperties()); } } @Override public boolean hasConfigurationServiceBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService == null) { return false; } return addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) != null && configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID)); } @Override @Override public SpringAppImpl withDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(true); return this; } @Override public SpringAppImpl withoutDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(false); return this; } @Override public SpringAppImpl withCustomDomain(String domain) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties()); return this; } @Override public SpringAppImpl withCustomDomain(String domain, String certThumbprint) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties().withThumbprint(certThumbprint)); return this; } @Override public Update withoutCustomDomain(String domain) { domains.prepareDelete(domain); return this; } @Override public SpringAppImpl withHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(true); return this; } @Override public SpringAppImpl withoutHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(false); return this; } @Override public SpringAppImpl withTemporaryDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withTemporaryDisk( new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withPersistentDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withPersistentDisk( new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withActiveDeployment(String name) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.setActiveDeploymentTask = context -> manager().serviceClient().getApps() .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) .then(context.voidMono()); return this; } @Override public void beforeGroupCreateOrUpdate() { if (setActiveDeploymentTask != null) { this.addPostRunDependent(setActiveDeploymentTask); } setActiveDeploymentTask = null; } @Override public Mono<SpringApp> createResourceAsync() { if (springAppDeploymentToCreate == null) { withDefaultActiveDeployment(); } return manager().serviceClient().getApps().createOrUpdateAsync( parent().resourceGroupName(), parent().name(), name(), new AppResourceInner()) .thenMany(springAppDeploymentToCreate.createAsync()) .then(updateResourceAsync()); } @Override public Mono<SpringApp> updateResourceAsync() { return manager().serviceClient().getApps().updateAsync( parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getApps().deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono<AppResourceInner> getInnerAsync() { return manager().serviceClient().getApps().getAsync(parent().resourceGroupName(), parent().name(), name()); } @Override public String id() { return innerModel().id(); } @Override public SpringAppImpl update() { prepareUpdate(); return this; } public AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl withServiceBinding(String name, BindingResourceProperties bindingProperties) { serviceBindings.prepareCreateOrUpdate(name, bindingProperties); return this; } @Override public SpringAppImpl withoutServiceBinding(String name) { serviceBindings.prepareDelete(name); return this; } @Override public SpringAppImpl withDefaultActiveDeployment() { String defaultDeploymentName = "default"; withActiveDeployment(defaultDeploymentName); springAppDeploymentToCreate = deployments().define(defaultDeploymentName) .withExistingSource(UserSourceType.JAR, String.format("<%s>", defaultDeploymentName)); return this; } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithAttach<? extends SpringApp.DefinitionStages.WithCreate, T>> SpringAppDeployment.DefinitionStages.Blank<T> defineActiveDeployment(String name) { return (SpringAppDeployment.DefinitionStages.Blank<T>) deployments.define(name); } SpringAppImpl addActiveDeployment(SpringAppDeploymentImpl deployment) { withActiveDeployment(deployment.name()); springAppDeploymentToCreate = deployment; return this; } @Override public SpringAppImpl withConfigurationServiceBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService != null) { Map<String, Object> configurationServiceConfigs = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, configurationService.id()); } return this; } @Override public SpringAppImpl withoutConfigurationServiceBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } @Override public SpringAppImpl withServiceRegistryBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry != null) { Map<String, Object> serviceRegistryConfigs = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); serviceRegistryConfigs.put(Constants.BINDING_RESOURCE_ID, serviceRegistry.id()); } return this; } @Override public SpringAppImpl withoutServiceRegistryBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.SERVICE_REGISTRY_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } }
class SpringAppImpl extends ExternalChildResourceImpl<SpringApp, AppResourceInner, SpringServiceImpl, SpringService> implements SpringApp, SpringApp.Definition, SpringApp.Update { private Creatable<SpringAppDeployment> springAppDeploymentToCreate = null; private final SpringAppDeploymentsImpl deployments = new SpringAppDeploymentsImpl(this); private final SpringAppServiceBindingsImpl serviceBindings = new SpringAppServiceBindingsImpl(this); private final SpringAppDomainsImpl domains = new SpringAppDomainsImpl(this); private FunctionalTaskItem setActiveDeploymentTask = null; SpringAppImpl(String name, SpringServiceImpl parent, AppResourceInner innerObject) { super(name, parent, innerObject); } @Override public boolean isPublic() { if (innerModel().properties() == null) { return false; } return innerModel().properties().publicProperty(); } @Override public boolean isHttpsOnly() { if (innerModel().properties() == null) { return false; } return innerModel().properties().httpsOnly(); } @Override public String url() { if (innerModel().properties() == null) { return null; } return innerModel().properties().url(); } @Override public String fqdn() { if (innerModel().properties() == null) { return null; } return innerModel().properties().fqdn(); } @Override public TemporaryDisk temporaryDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().temporaryDisk(); } @Override public PersistentDisk persistentDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().persistentDisk(); } @Override public ManagedIdentityProperties identity() { return innerModel().identity(); } @Override public String activeDeploymentName() { Optional<SpringAppDeployment> deployment = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); return deployment.map(SpringAppDeployment::appName).orElse(null); } @Override public SpringAppDeployment getActiveDeployment() { return getActiveDeploymentAsync().block(); } @Override public Mono<SpringAppDeployment> getActiveDeploymentAsync() { return deployments.listAsync().filter(SpringAppDeployment::isActive).singleOrEmpty(); } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithCreate<T>> SpringAppDeployments<T> deployments() { return (SpringAppDeployments<T>) deployments; } @Override public SpringAppServiceBindings serviceBindings() { return serviceBindings; } @Override public SpringAppDomains customDomains() { return domains; } @Override public Mono<ResourceUploadDefinition> getResourceUploadUrlAsync() { return manager().serviceClient().getApps().getResourceUploadUrlAsync( parent().resourceGroupName(), parent().name(), name()); } @Override public ResourceUploadDefinition getResourceUploadUrl() { return getResourceUploadUrlAsync().block(); } private void ensureProperty() { if (innerModel().properties() == null) { innerModel().withProperties(new AppResourceProperties()); } } @Override public boolean hasConfigurationServiceBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService == null) { return false; } return addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) != null && configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID)); } @Override @Override public SpringAppImpl withDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(true); return this; } @Override public SpringAppImpl withoutDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(false); return this; } @Override public SpringAppImpl withCustomDomain(String domain) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties()); return this; } @Override public SpringAppImpl withCustomDomain(String domain, String certThumbprint) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties().withThumbprint(certThumbprint)); return this; } @Override public Update withoutCustomDomain(String domain) { domains.prepareDelete(domain); return this; } @Override public SpringAppImpl withHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(true); return this; } @Override public SpringAppImpl withoutHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(false); return this; } @Override public SpringAppImpl withTemporaryDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withTemporaryDisk( new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withPersistentDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withPersistentDisk( new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withActiveDeployment(String name) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.setActiveDeploymentTask = context -> manager().serviceClient().getApps() .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) .then(context.voidMono()); return this; } @Override public void beforeGroupCreateOrUpdate() { if (setActiveDeploymentTask != null) { this.addPostRunDependent(setActiveDeploymentTask); } setActiveDeploymentTask = null; } @Override public Mono<SpringApp> createResourceAsync() { if (springAppDeploymentToCreate == null) { withDefaultActiveDeployment(); } return manager().serviceClient().getApps().createOrUpdateAsync( parent().resourceGroupName(), parent().name(), name(), new AppResourceInner()) .thenMany(springAppDeploymentToCreate.createAsync()) .then(updateResourceAsync()); } @Override public Mono<SpringApp> updateResourceAsync() { return manager().serviceClient().getApps().updateAsync( parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getApps().deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono<AppResourceInner> getInnerAsync() { return manager().serviceClient().getApps().getAsync(parent().resourceGroupName(), parent().name(), name()); } @Override public String id() { return innerModel().id(); } @Override public SpringAppImpl update() { prepareUpdate(); return this; } public AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl withServiceBinding(String name, BindingResourceProperties bindingProperties) { serviceBindings.prepareCreateOrUpdate(name, bindingProperties); return this; } @Override public SpringAppImpl withoutServiceBinding(String name) { serviceBindings.prepareDelete(name); return this; } @Override public SpringAppImpl withDefaultActiveDeployment() { String defaultDeploymentName = "default"; withActiveDeployment(defaultDeploymentName); springAppDeploymentToCreate = deployments().define(defaultDeploymentName) .withExistingSource(UserSourceType.JAR, String.format("<%s>", defaultDeploymentName)); return this; } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithAttach<? extends SpringApp.DefinitionStages.WithCreate, T>> SpringAppDeployment.DefinitionStages.Blank<T> defineActiveDeployment(String name) { return (SpringAppDeployment.DefinitionStages.Blank<T>) deployments.define(name); } SpringAppImpl addActiveDeployment(SpringAppDeploymentImpl deployment) { withActiveDeployment(deployment.name()); springAppDeploymentToCreate = deployment; return this; } @Override public SpringAppImpl withConfigurationServiceBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService != null) { Map<String, Object> configurationServiceConfigs = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, configurationService.id()); } return this; } @Override public SpringAppImpl withoutConfigurationServiceBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } @Override public SpringAppImpl withServiceRegistryBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry != null) { Map<String, Object> serviceRegistryConfigs = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); serviceRegistryConfigs.put(Constants.BINDING_RESOURCE_ID, serviceRegistry.id()); } return this; } @Override public SpringAppImpl withoutServiceRegistryBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.SERVICE_REGISTRY_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } }
`serviceRegistry` is from remote request and `id` is from its `innerModel().id()`. If service registry itself is not null, its id can't be null I assume.
public boolean hasServiceRegistryBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry == null) { return false; } return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); }
&& serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID));
public boolean hasServiceRegistryBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry == null) { return false; } return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); }
class SpringAppImpl extends ExternalChildResourceImpl<SpringApp, AppResourceInner, SpringServiceImpl, SpringService> implements SpringApp, SpringApp.Definition, SpringApp.Update { private Creatable<SpringAppDeployment> springAppDeploymentToCreate = null; private final SpringAppDeploymentsImpl deployments = new SpringAppDeploymentsImpl(this); private final SpringAppServiceBindingsImpl serviceBindings = new SpringAppServiceBindingsImpl(this); private final SpringAppDomainsImpl domains = new SpringAppDomainsImpl(this); private FunctionalTaskItem setActiveDeploymentTask = null; SpringAppImpl(String name, SpringServiceImpl parent, AppResourceInner innerObject) { super(name, parent, innerObject); } @Override public boolean isPublic() { if (innerModel().properties() == null) { return false; } return innerModel().properties().publicProperty(); } @Override public boolean isHttpsOnly() { if (innerModel().properties() == null) { return false; } return innerModel().properties().httpsOnly(); } @Override public String url() { if (innerModel().properties() == null) { return null; } return innerModel().properties().url(); } @Override public String fqdn() { if (innerModel().properties() == null) { return null; } return innerModel().properties().fqdn(); } @Override public TemporaryDisk temporaryDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().temporaryDisk(); } @Override public PersistentDisk persistentDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().persistentDisk(); } @Override public ManagedIdentityProperties identity() { return innerModel().identity(); } @Override public String activeDeploymentName() { Optional<SpringAppDeployment> deployment = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); return deployment.map(SpringAppDeployment::appName).orElse(null); } @Override public SpringAppDeployment getActiveDeployment() { return getActiveDeploymentAsync().block(); } @Override public Mono<SpringAppDeployment> getActiveDeploymentAsync() { return deployments.listAsync().filter(SpringAppDeployment::isActive).singleOrEmpty(); } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithCreate<T>> SpringAppDeployments<T> deployments() { return (SpringAppDeployments<T>) deployments; } @Override public SpringAppServiceBindings serviceBindings() { return serviceBindings; } @Override public SpringAppDomains customDomains() { return domains; } @Override public Mono<ResourceUploadDefinition> getResourceUploadUrlAsync() { return manager().serviceClient().getApps().getResourceUploadUrlAsync( parent().resourceGroupName(), parent().name(), name()); } @Override public ResourceUploadDefinition getResourceUploadUrl() { return getResourceUploadUrlAsync().block(); } private void ensureProperty() { if (innerModel().properties() == null) { innerModel().withProperties(new AppResourceProperties()); } } @Override public boolean hasConfigurationServiceBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService == null) { return false; } return addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) != null && configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID)); } @Override @Override public SpringAppImpl withDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(true); return this; } @Override public SpringAppImpl withoutDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(false); return this; } @Override public SpringAppImpl withCustomDomain(String domain) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties()); return this; } @Override public SpringAppImpl withCustomDomain(String domain, String certThumbprint) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties().withThumbprint(certThumbprint)); return this; } @Override public Update withoutCustomDomain(String domain) { domains.prepareDelete(domain); return this; } @Override public SpringAppImpl withHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(true); return this; } @Override public SpringAppImpl withoutHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(false); return this; } @Override public SpringAppImpl withTemporaryDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withTemporaryDisk( new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withPersistentDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withPersistentDisk( new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withActiveDeployment(String name) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.setActiveDeploymentTask = context -> manager().serviceClient().getApps() .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) .then(context.voidMono()); return this; } @Override public void beforeGroupCreateOrUpdate() { if (setActiveDeploymentTask != null) { this.addPostRunDependent(setActiveDeploymentTask); } setActiveDeploymentTask = null; } @Override public Mono<SpringApp> createResourceAsync() { if (springAppDeploymentToCreate == null) { withDefaultActiveDeployment(); } return manager().serviceClient().getApps().createOrUpdateAsync( parent().resourceGroupName(), parent().name(), name(), new AppResourceInner()) .thenMany(springAppDeploymentToCreate.createAsync()) .then(updateResourceAsync()); } @Override public Mono<SpringApp> updateResourceAsync() { return manager().serviceClient().getApps().updateAsync( parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getApps().deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono<AppResourceInner> getInnerAsync() { return manager().serviceClient().getApps().getAsync(parent().resourceGroupName(), parent().name(), name()); } @Override public String id() { return innerModel().id(); } @Override public SpringAppImpl update() { prepareUpdate(); return this; } public AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl withServiceBinding(String name, BindingResourceProperties bindingProperties) { serviceBindings.prepareCreateOrUpdate(name, bindingProperties); return this; } @Override public SpringAppImpl withoutServiceBinding(String name) { serviceBindings.prepareDelete(name); return this; } @Override public SpringAppImpl withDefaultActiveDeployment() { String defaultDeploymentName = "default"; withActiveDeployment(defaultDeploymentName); springAppDeploymentToCreate = deployments().define(defaultDeploymentName) .withExistingSource(UserSourceType.JAR, String.format("<%s>", defaultDeploymentName)); return this; } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithAttach<? extends SpringApp.DefinitionStages.WithCreate, T>> SpringAppDeployment.DefinitionStages.Blank<T> defineActiveDeployment(String name) { return (SpringAppDeployment.DefinitionStages.Blank<T>) deployments.define(name); } SpringAppImpl addActiveDeployment(SpringAppDeploymentImpl deployment) { withActiveDeployment(deployment.name()); springAppDeploymentToCreate = deployment; return this; } @Override public SpringAppImpl withConfigurationServiceBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService != null) { Map<String, Object> configurationServiceConfigs = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, configurationService.id()); } return this; } @Override public SpringAppImpl withoutConfigurationServiceBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } @Override public SpringAppImpl withServiceRegistryBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry != null) { Map<String, Object> serviceRegistryConfigs = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); serviceRegistryConfigs.put(Constants.BINDING_RESOURCE_ID, serviceRegistry.id()); } return this; } @Override public SpringAppImpl withoutServiceRegistryBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.SERVICE_REGISTRY_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } }
class SpringAppImpl extends ExternalChildResourceImpl<SpringApp, AppResourceInner, SpringServiceImpl, SpringService> implements SpringApp, SpringApp.Definition, SpringApp.Update { private Creatable<SpringAppDeployment> springAppDeploymentToCreate = null; private final SpringAppDeploymentsImpl deployments = new SpringAppDeploymentsImpl(this); private final SpringAppServiceBindingsImpl serviceBindings = new SpringAppServiceBindingsImpl(this); private final SpringAppDomainsImpl domains = new SpringAppDomainsImpl(this); private FunctionalTaskItem setActiveDeploymentTask = null; SpringAppImpl(String name, SpringServiceImpl parent, AppResourceInner innerObject) { super(name, parent, innerObject); } @Override public boolean isPublic() { if (innerModel().properties() == null) { return false; } return innerModel().properties().publicProperty(); } @Override public boolean isHttpsOnly() { if (innerModel().properties() == null) { return false; } return innerModel().properties().httpsOnly(); } @Override public String url() { if (innerModel().properties() == null) { return null; } return innerModel().properties().url(); } @Override public String fqdn() { if (innerModel().properties() == null) { return null; } return innerModel().properties().fqdn(); } @Override public TemporaryDisk temporaryDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().temporaryDisk(); } @Override public PersistentDisk persistentDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().persistentDisk(); } @Override public ManagedIdentityProperties identity() { return innerModel().identity(); } @Override public String activeDeploymentName() { Optional<SpringAppDeployment> deployment = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); return deployment.map(SpringAppDeployment::appName).orElse(null); } @Override public SpringAppDeployment getActiveDeployment() { return getActiveDeploymentAsync().block(); } @Override public Mono<SpringAppDeployment> getActiveDeploymentAsync() { return deployments.listAsync().filter(SpringAppDeployment::isActive).singleOrEmpty(); } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithCreate<T>> SpringAppDeployments<T> deployments() { return (SpringAppDeployments<T>) deployments; } @Override public SpringAppServiceBindings serviceBindings() { return serviceBindings; } @Override public SpringAppDomains customDomains() { return domains; } @Override public Mono<ResourceUploadDefinition> getResourceUploadUrlAsync() { return manager().serviceClient().getApps().getResourceUploadUrlAsync( parent().resourceGroupName(), parent().name(), name()); } @Override public ResourceUploadDefinition getResourceUploadUrl() { return getResourceUploadUrlAsync().block(); } private void ensureProperty() { if (innerModel().properties() == null) { innerModel().withProperties(new AppResourceProperties()); } } @Override public boolean hasConfigurationServiceBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService == null) { return false; } return addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) != null && configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID)); } @Override @Override public SpringAppImpl withDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(true); return this; } @Override public SpringAppImpl withoutDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(false); return this; } @Override public SpringAppImpl withCustomDomain(String domain) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties()); return this; } @Override public SpringAppImpl withCustomDomain(String domain, String certThumbprint) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties().withThumbprint(certThumbprint)); return this; } @Override public Update withoutCustomDomain(String domain) { domains.prepareDelete(domain); return this; } @Override public SpringAppImpl withHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(true); return this; } @Override public SpringAppImpl withoutHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(false); return this; } @Override public SpringAppImpl withTemporaryDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withTemporaryDisk( new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withPersistentDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withPersistentDisk( new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withActiveDeployment(String name) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.setActiveDeploymentTask = context -> manager().serviceClient().getApps() .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) .then(context.voidMono()); return this; } @Override public void beforeGroupCreateOrUpdate() { if (setActiveDeploymentTask != null) { this.addPostRunDependent(setActiveDeploymentTask); } setActiveDeploymentTask = null; } @Override public Mono<SpringApp> createResourceAsync() { if (springAppDeploymentToCreate == null) { withDefaultActiveDeployment(); } return manager().serviceClient().getApps().createOrUpdateAsync( parent().resourceGroupName(), parent().name(), name(), new AppResourceInner()) .thenMany(springAppDeploymentToCreate.createAsync()) .then(updateResourceAsync()); } @Override public Mono<SpringApp> updateResourceAsync() { return manager().serviceClient().getApps().updateAsync( parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getApps().deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono<AppResourceInner> getInnerAsync() { return manager().serviceClient().getApps().getAsync(parent().resourceGroupName(), parent().name(), name()); } @Override public String id() { return innerModel().id(); } @Override public SpringAppImpl update() { prepareUpdate(); return this; } public AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl withServiceBinding(String name, BindingResourceProperties bindingProperties) { serviceBindings.prepareCreateOrUpdate(name, bindingProperties); return this; } @Override public SpringAppImpl withoutServiceBinding(String name) { serviceBindings.prepareDelete(name); return this; } @Override public SpringAppImpl withDefaultActiveDeployment() { String defaultDeploymentName = "default"; withActiveDeployment(defaultDeploymentName); springAppDeploymentToCreate = deployments().define(defaultDeploymentName) .withExistingSource(UserSourceType.JAR, String.format("<%s>", defaultDeploymentName)); return this; } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithAttach<? extends SpringApp.DefinitionStages.WithCreate, T>> SpringAppDeployment.DefinitionStages.Blank<T> defineActiveDeployment(String name) { return (SpringAppDeployment.DefinitionStages.Blank<T>) deployments.define(name); } SpringAppImpl addActiveDeployment(SpringAppDeploymentImpl deployment) { withActiveDeployment(deployment.name()); springAppDeploymentToCreate = deployment; return this; } @Override public SpringAppImpl withConfigurationServiceBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService != null) { Map<String, Object> configurationServiceConfigs = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, configurationService.id()); } return this; } @Override public SpringAppImpl withoutConfigurationServiceBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } @Override public SpringAppImpl withServiceRegistryBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry != null) { Map<String, Object> serviceRegistryConfigs = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); serviceRegistryConfigs.put(Constants.BINDING_RESOURCE_ID, serviceRegistry.id()); } return this; } @Override public SpringAppImpl withoutServiceRegistryBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.SERVICE_REGISTRY_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } }
why we use equalsIgnoreCase?
public boolean hasConfigurationServiceBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService == null) { return false; } return addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) != null && configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID)); }
&& configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID));
public boolean hasConfigurationServiceBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService == null) { return false; } return addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) != null && configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID)); }
class SpringAppImpl extends ExternalChildResourceImpl<SpringApp, AppResourceInner, SpringServiceImpl, SpringService> implements SpringApp, SpringApp.Definition, SpringApp.Update { private Creatable<SpringAppDeployment> springAppDeploymentToCreate = null; private final SpringAppDeploymentsImpl deployments = new SpringAppDeploymentsImpl(this); private final SpringAppServiceBindingsImpl serviceBindings = new SpringAppServiceBindingsImpl(this); private final SpringAppDomainsImpl domains = new SpringAppDomainsImpl(this); private FunctionalTaskItem setActiveDeploymentTask = null; SpringAppImpl(String name, SpringServiceImpl parent, AppResourceInner innerObject) { super(name, parent, innerObject); } @Override public boolean isPublic() { if (innerModel().properties() == null) { return false; } return innerModel().properties().publicProperty(); } @Override public boolean isHttpsOnly() { if (innerModel().properties() == null) { return false; } return innerModel().properties().httpsOnly(); } @Override public String url() { if (innerModel().properties() == null) { return null; } return innerModel().properties().url(); } @Override public String fqdn() { if (innerModel().properties() == null) { return null; } return innerModel().properties().fqdn(); } @Override public TemporaryDisk temporaryDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().temporaryDisk(); } @Override public PersistentDisk persistentDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().persistentDisk(); } @Override public ManagedIdentityProperties identity() { return innerModel().identity(); } @Override public String activeDeploymentName() { Optional<SpringAppDeployment> deployment = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); return deployment.map(SpringAppDeployment::appName).orElse(null); } @Override public SpringAppDeployment getActiveDeployment() { return getActiveDeploymentAsync().block(); } @Override public Mono<SpringAppDeployment> getActiveDeploymentAsync() { return deployments.listAsync().filter(SpringAppDeployment::isActive).singleOrEmpty(); } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithCreate<T>> SpringAppDeployments<T> deployments() { return (SpringAppDeployments<T>) deployments; } @Override public SpringAppServiceBindings serviceBindings() { return serviceBindings; } @Override public SpringAppDomains customDomains() { return domains; } @Override public Mono<ResourceUploadDefinition> getResourceUploadUrlAsync() { return manager().serviceClient().getApps().getResourceUploadUrlAsync( parent().resourceGroupName(), parent().name(), name()); } @Override public ResourceUploadDefinition getResourceUploadUrl() { return getResourceUploadUrlAsync().block(); } private void ensureProperty() { if (innerModel().properties() == null) { innerModel().withProperties(new AppResourceProperties()); } } @Override @Override public boolean hasServiceRegistryBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry == null) { return false; } return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); } @Override public SpringAppImpl withDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(true); return this; } @Override public SpringAppImpl withoutDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(false); return this; } @Override public SpringAppImpl withCustomDomain(String domain) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties()); return this; } @Override public SpringAppImpl withCustomDomain(String domain, String certThumbprint) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties().withThumbprint(certThumbprint)); return this; } @Override public Update withoutCustomDomain(String domain) { domains.prepareDelete(domain); return this; } @Override public SpringAppImpl withHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(true); return this; } @Override public SpringAppImpl withoutHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(false); return this; } @Override public SpringAppImpl withTemporaryDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withTemporaryDisk( new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withPersistentDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withPersistentDisk( new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withActiveDeployment(String name) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.setActiveDeploymentTask = context -> manager().serviceClient().getApps() .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) .then(context.voidMono()); return this; } @Override public void beforeGroupCreateOrUpdate() { if (setActiveDeploymentTask != null) { this.addPostRunDependent(setActiveDeploymentTask); } setActiveDeploymentTask = null; } @Override public Mono<SpringApp> createResourceAsync() { if (springAppDeploymentToCreate == null) { withDefaultActiveDeployment(); } return manager().serviceClient().getApps().createOrUpdateAsync( parent().resourceGroupName(), parent().name(), name(), new AppResourceInner()) .thenMany(springAppDeploymentToCreate.createAsync()) .then(updateResourceAsync()); } @Override public Mono<SpringApp> updateResourceAsync() { return manager().serviceClient().getApps().updateAsync( parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getApps().deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono<AppResourceInner> getInnerAsync() { return manager().serviceClient().getApps().getAsync(parent().resourceGroupName(), parent().name(), name()); } @Override public String id() { return innerModel().id(); } @Override public SpringAppImpl update() { prepareUpdate(); return this; } public AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl withServiceBinding(String name, BindingResourceProperties bindingProperties) { serviceBindings.prepareCreateOrUpdate(name, bindingProperties); return this; } @Override public SpringAppImpl withoutServiceBinding(String name) { serviceBindings.prepareDelete(name); return this; } @Override public SpringAppImpl withDefaultActiveDeployment() { String defaultDeploymentName = "default"; withActiveDeployment(defaultDeploymentName); springAppDeploymentToCreate = deployments().define(defaultDeploymentName) .withExistingSource(UserSourceType.JAR, String.format("<%s>", defaultDeploymentName)); return this; } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithAttach<? extends SpringApp.DefinitionStages.WithCreate, T>> SpringAppDeployment.DefinitionStages.Blank<T> defineActiveDeployment(String name) { return (SpringAppDeployment.DefinitionStages.Blank<T>) deployments.define(name); } SpringAppImpl addActiveDeployment(SpringAppDeploymentImpl deployment) { withActiveDeployment(deployment.name()); springAppDeploymentToCreate = deployment; return this; } @Override public SpringAppImpl withConfigurationServiceBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService != null) { Map<String, Object> configurationServiceConfigs = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, configurationService.id()); } return this; } @Override public SpringAppImpl withoutConfigurationServiceBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } @Override public SpringAppImpl withServiceRegistryBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry != null) { Map<String, Object> serviceRegistryConfigs = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); serviceRegistryConfigs.put(Constants.BINDING_RESOURCE_ID, serviceRegistry.id()); } return this; } @Override public SpringAppImpl withoutServiceRegistryBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.SERVICE_REGISTRY_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } }
class SpringAppImpl extends ExternalChildResourceImpl<SpringApp, AppResourceInner, SpringServiceImpl, SpringService> implements SpringApp, SpringApp.Definition, SpringApp.Update { private Creatable<SpringAppDeployment> springAppDeploymentToCreate = null; private final SpringAppDeploymentsImpl deployments = new SpringAppDeploymentsImpl(this); private final SpringAppServiceBindingsImpl serviceBindings = new SpringAppServiceBindingsImpl(this); private final SpringAppDomainsImpl domains = new SpringAppDomainsImpl(this); private FunctionalTaskItem setActiveDeploymentTask = null; SpringAppImpl(String name, SpringServiceImpl parent, AppResourceInner innerObject) { super(name, parent, innerObject); } @Override public boolean isPublic() { if (innerModel().properties() == null) { return false; } return innerModel().properties().publicProperty(); } @Override public boolean isHttpsOnly() { if (innerModel().properties() == null) { return false; } return innerModel().properties().httpsOnly(); } @Override public String url() { if (innerModel().properties() == null) { return null; } return innerModel().properties().url(); } @Override public String fqdn() { if (innerModel().properties() == null) { return null; } return innerModel().properties().fqdn(); } @Override public TemporaryDisk temporaryDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().temporaryDisk(); } @Override public PersistentDisk persistentDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().persistentDisk(); } @Override public ManagedIdentityProperties identity() { return innerModel().identity(); } @Override public String activeDeploymentName() { Optional<SpringAppDeployment> deployment = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); return deployment.map(SpringAppDeployment::appName).orElse(null); } @Override public SpringAppDeployment getActiveDeployment() { return getActiveDeploymentAsync().block(); } @Override public Mono<SpringAppDeployment> getActiveDeploymentAsync() { return deployments.listAsync().filter(SpringAppDeployment::isActive).singleOrEmpty(); } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithCreate<T>> SpringAppDeployments<T> deployments() { return (SpringAppDeployments<T>) deployments; } @Override public SpringAppServiceBindings serviceBindings() { return serviceBindings; } @Override public SpringAppDomains customDomains() { return domains; } @Override public Mono<ResourceUploadDefinition> getResourceUploadUrlAsync() { return manager().serviceClient().getApps().getResourceUploadUrlAsync( parent().resourceGroupName(), parent().name(), name()); } @Override public ResourceUploadDefinition getResourceUploadUrl() { return getResourceUploadUrlAsync().block(); } private void ensureProperty() { if (innerModel().properties() == null) { innerModel().withProperties(new AppResourceProperties()); } } @Override @Override public boolean hasServiceRegistryBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry == null) { return false; } return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); } @Override public SpringAppImpl withDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(true); return this; } @Override public SpringAppImpl withoutDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(false); return this; } @Override public SpringAppImpl withCustomDomain(String domain) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties()); return this; } @Override public SpringAppImpl withCustomDomain(String domain, String certThumbprint) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties().withThumbprint(certThumbprint)); return this; } @Override public Update withoutCustomDomain(String domain) { domains.prepareDelete(domain); return this; } @Override public SpringAppImpl withHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(true); return this; } @Override public SpringAppImpl withoutHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(false); return this; } @Override public SpringAppImpl withTemporaryDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withTemporaryDisk( new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withPersistentDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withPersistentDisk( new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withActiveDeployment(String name) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.setActiveDeploymentTask = context -> manager().serviceClient().getApps() .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) .then(context.voidMono()); return this; } @Override public void beforeGroupCreateOrUpdate() { if (setActiveDeploymentTask != null) { this.addPostRunDependent(setActiveDeploymentTask); } setActiveDeploymentTask = null; } @Override public Mono<SpringApp> createResourceAsync() { if (springAppDeploymentToCreate == null) { withDefaultActiveDeployment(); } return manager().serviceClient().getApps().createOrUpdateAsync( parent().resourceGroupName(), parent().name(), name(), new AppResourceInner()) .thenMany(springAppDeploymentToCreate.createAsync()) .then(updateResourceAsync()); } @Override public Mono<SpringApp> updateResourceAsync() { return manager().serviceClient().getApps().updateAsync( parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getApps().deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono<AppResourceInner> getInnerAsync() { return manager().serviceClient().getApps().getAsync(parent().resourceGroupName(), parent().name(), name()); } @Override public String id() { return innerModel().id(); } @Override public SpringAppImpl update() { prepareUpdate(); return this; } public AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl withServiceBinding(String name, BindingResourceProperties bindingProperties) { serviceBindings.prepareCreateOrUpdate(name, bindingProperties); return this; } @Override public SpringAppImpl withoutServiceBinding(String name) { serviceBindings.prepareDelete(name); return this; } @Override public SpringAppImpl withDefaultActiveDeployment() { String defaultDeploymentName = "default"; withActiveDeployment(defaultDeploymentName); springAppDeploymentToCreate = deployments().define(defaultDeploymentName) .withExistingSource(UserSourceType.JAR, String.format("<%s>", defaultDeploymentName)); return this; } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithAttach<? extends SpringApp.DefinitionStages.WithCreate, T>> SpringAppDeployment.DefinitionStages.Blank<T> defineActiveDeployment(String name) { return (SpringAppDeployment.DefinitionStages.Blank<T>) deployments.define(name); } SpringAppImpl addActiveDeployment(SpringAppDeploymentImpl deployment) { withActiveDeployment(deployment.name()); springAppDeploymentToCreate = deployment; return this; } @Override public SpringAppImpl withConfigurationServiceBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService != null) { Map<String, Object> configurationServiceConfigs = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, configurationService.id()); } return this; } @Override public SpringAppImpl withoutConfigurationServiceBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } @Override public SpringAppImpl withServiceRegistryBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry != null) { Map<String, Object> serviceRegistryConfigs = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); serviceRegistryConfigs.put(Constants.BINDING_RESOURCE_ID, serviceRegistry.id()); } return this; } @Override public SpringAppImpl withoutServiceRegistryBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.SERVICE_REGISTRY_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } }
I just learnt that resource names are usually case-insensitive according to the doc: https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/resource-name-rules > Resource names are case-insensitive unless noted in the valid characters column. So I changed it just in case.
public boolean hasConfigurationServiceBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService == null) { return false; } return addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) != null && configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID)); }
&& configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID));
public boolean hasConfigurationServiceBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService == null) { return false; } return addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) != null && configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID)); }
class SpringAppImpl extends ExternalChildResourceImpl<SpringApp, AppResourceInner, SpringServiceImpl, SpringService> implements SpringApp, SpringApp.Definition, SpringApp.Update { private Creatable<SpringAppDeployment> springAppDeploymentToCreate = null; private final SpringAppDeploymentsImpl deployments = new SpringAppDeploymentsImpl(this); private final SpringAppServiceBindingsImpl serviceBindings = new SpringAppServiceBindingsImpl(this); private final SpringAppDomainsImpl domains = new SpringAppDomainsImpl(this); private FunctionalTaskItem setActiveDeploymentTask = null; SpringAppImpl(String name, SpringServiceImpl parent, AppResourceInner innerObject) { super(name, parent, innerObject); } @Override public boolean isPublic() { if (innerModel().properties() == null) { return false; } return innerModel().properties().publicProperty(); } @Override public boolean isHttpsOnly() { if (innerModel().properties() == null) { return false; } return innerModel().properties().httpsOnly(); } @Override public String url() { if (innerModel().properties() == null) { return null; } return innerModel().properties().url(); } @Override public String fqdn() { if (innerModel().properties() == null) { return null; } return innerModel().properties().fqdn(); } @Override public TemporaryDisk temporaryDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().temporaryDisk(); } @Override public PersistentDisk persistentDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().persistentDisk(); } @Override public ManagedIdentityProperties identity() { return innerModel().identity(); } @Override public String activeDeploymentName() { Optional<SpringAppDeployment> deployment = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); return deployment.map(SpringAppDeployment::appName).orElse(null); } @Override public SpringAppDeployment getActiveDeployment() { return getActiveDeploymentAsync().block(); } @Override public Mono<SpringAppDeployment> getActiveDeploymentAsync() { return deployments.listAsync().filter(SpringAppDeployment::isActive).singleOrEmpty(); } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithCreate<T>> SpringAppDeployments<T> deployments() { return (SpringAppDeployments<T>) deployments; } @Override public SpringAppServiceBindings serviceBindings() { return serviceBindings; } @Override public SpringAppDomains customDomains() { return domains; } @Override public Mono<ResourceUploadDefinition> getResourceUploadUrlAsync() { return manager().serviceClient().getApps().getResourceUploadUrlAsync( parent().resourceGroupName(), parent().name(), name()); } @Override public ResourceUploadDefinition getResourceUploadUrl() { return getResourceUploadUrlAsync().block(); } private void ensureProperty() { if (innerModel().properties() == null) { innerModel().withProperties(new AppResourceProperties()); } } @Override @Override public boolean hasServiceRegistryBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry == null) { return false; } return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); } @Override public SpringAppImpl withDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(true); return this; } @Override public SpringAppImpl withoutDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(false); return this; } @Override public SpringAppImpl withCustomDomain(String domain) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties()); return this; } @Override public SpringAppImpl withCustomDomain(String domain, String certThumbprint) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties().withThumbprint(certThumbprint)); return this; } @Override public Update withoutCustomDomain(String domain) { domains.prepareDelete(domain); return this; } @Override public SpringAppImpl withHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(true); return this; } @Override public SpringAppImpl withoutHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(false); return this; } @Override public SpringAppImpl withTemporaryDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withTemporaryDisk( new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withPersistentDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withPersistentDisk( new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withActiveDeployment(String name) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.setActiveDeploymentTask = context -> manager().serviceClient().getApps() .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) .then(context.voidMono()); return this; } @Override public void beforeGroupCreateOrUpdate() { if (setActiveDeploymentTask != null) { this.addPostRunDependent(setActiveDeploymentTask); } setActiveDeploymentTask = null; } @Override public Mono<SpringApp> createResourceAsync() { if (springAppDeploymentToCreate == null) { withDefaultActiveDeployment(); } return manager().serviceClient().getApps().createOrUpdateAsync( parent().resourceGroupName(), parent().name(), name(), new AppResourceInner()) .thenMany(springAppDeploymentToCreate.createAsync()) .then(updateResourceAsync()); } @Override public Mono<SpringApp> updateResourceAsync() { return manager().serviceClient().getApps().updateAsync( parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getApps().deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono<AppResourceInner> getInnerAsync() { return manager().serviceClient().getApps().getAsync(parent().resourceGroupName(), parent().name(), name()); } @Override public String id() { return innerModel().id(); } @Override public SpringAppImpl update() { prepareUpdate(); return this; } public AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl withServiceBinding(String name, BindingResourceProperties bindingProperties) { serviceBindings.prepareCreateOrUpdate(name, bindingProperties); return this; } @Override public SpringAppImpl withoutServiceBinding(String name) { serviceBindings.prepareDelete(name); return this; } @Override public SpringAppImpl withDefaultActiveDeployment() { String defaultDeploymentName = "default"; withActiveDeployment(defaultDeploymentName); springAppDeploymentToCreate = deployments().define(defaultDeploymentName) .withExistingSource(UserSourceType.JAR, String.format("<%s>", defaultDeploymentName)); return this; } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithAttach<? extends SpringApp.DefinitionStages.WithCreate, T>> SpringAppDeployment.DefinitionStages.Blank<T> defineActiveDeployment(String name) { return (SpringAppDeployment.DefinitionStages.Blank<T>) deployments.define(name); } SpringAppImpl addActiveDeployment(SpringAppDeploymentImpl deployment) { withActiveDeployment(deployment.name()); springAppDeploymentToCreate = deployment; return this; } @Override public SpringAppImpl withConfigurationServiceBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService != null) { Map<String, Object> configurationServiceConfigs = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, configurationService.id()); } return this; } @Override public SpringAppImpl withoutConfigurationServiceBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } @Override public SpringAppImpl withServiceRegistryBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry != null) { Map<String, Object> serviceRegistryConfigs = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); serviceRegistryConfigs.put(Constants.BINDING_RESOURCE_ID, serviceRegistry.id()); } return this; } @Override public SpringAppImpl withoutServiceRegistryBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.SERVICE_REGISTRY_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } }
class SpringAppImpl extends ExternalChildResourceImpl<SpringApp, AppResourceInner, SpringServiceImpl, SpringService> implements SpringApp, SpringApp.Definition, SpringApp.Update { private Creatable<SpringAppDeployment> springAppDeploymentToCreate = null; private final SpringAppDeploymentsImpl deployments = new SpringAppDeploymentsImpl(this); private final SpringAppServiceBindingsImpl serviceBindings = new SpringAppServiceBindingsImpl(this); private final SpringAppDomainsImpl domains = new SpringAppDomainsImpl(this); private FunctionalTaskItem setActiveDeploymentTask = null; SpringAppImpl(String name, SpringServiceImpl parent, AppResourceInner innerObject) { super(name, parent, innerObject); } @Override public boolean isPublic() { if (innerModel().properties() == null) { return false; } return innerModel().properties().publicProperty(); } @Override public boolean isHttpsOnly() { if (innerModel().properties() == null) { return false; } return innerModel().properties().httpsOnly(); } @Override public String url() { if (innerModel().properties() == null) { return null; } return innerModel().properties().url(); } @Override public String fqdn() { if (innerModel().properties() == null) { return null; } return innerModel().properties().fqdn(); } @Override public TemporaryDisk temporaryDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().temporaryDisk(); } @Override public PersistentDisk persistentDisk() { if (innerModel().properties() == null) { return null; } return innerModel().properties().persistentDisk(); } @Override public ManagedIdentityProperties identity() { return innerModel().identity(); } @Override public String activeDeploymentName() { Optional<SpringAppDeployment> deployment = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); return deployment.map(SpringAppDeployment::appName).orElse(null); } @Override public SpringAppDeployment getActiveDeployment() { return getActiveDeploymentAsync().block(); } @Override public Mono<SpringAppDeployment> getActiveDeploymentAsync() { return deployments.listAsync().filter(SpringAppDeployment::isActive).singleOrEmpty(); } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithCreate<T>> SpringAppDeployments<T> deployments() { return (SpringAppDeployments<T>) deployments; } @Override public SpringAppServiceBindings serviceBindings() { return serviceBindings; } @Override public SpringAppDomains customDomains() { return domains; } @Override public Mono<ResourceUploadDefinition> getResourceUploadUrlAsync() { return manager().serviceClient().getApps().getResourceUploadUrlAsync( parent().resourceGroupName(), parent().name(), name()); } @Override public ResourceUploadDefinition getResourceUploadUrl() { return getResourceUploadUrlAsync().block(); } private void ensureProperty() { if (innerModel().properties() == null) { innerModel().withProperties(new AppResourceProperties()); } } @Override @Override public boolean hasServiceRegistryBinding() { Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return false; } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry == null) { return false; } return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); } @Override public SpringAppImpl withDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(true); return this; } @Override public SpringAppImpl withoutDefaultPublicEndpoint() { ensureProperty(); innerModel().properties().withPublicProperty(false); return this; } @Override public SpringAppImpl withCustomDomain(String domain) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties()); return this; } @Override public SpringAppImpl withCustomDomain(String domain, String certThumbprint) { domains.prepareCreateOrUpdate(domain, new CustomDomainProperties().withThumbprint(certThumbprint)); return this; } @Override public Update withoutCustomDomain(String domain) { domains.prepareDelete(domain); return this; } @Override public SpringAppImpl withHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(true); return this; } @Override public SpringAppImpl withoutHttpsOnly() { ensureProperty(); innerModel().properties().withHttpsOnly(false); return this; } @Override public SpringAppImpl withTemporaryDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withTemporaryDisk( new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withPersistentDisk(int sizeInGB, String mountPath) { ensureProperty(); innerModel().properties().withPersistentDisk( new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withActiveDeployment(String name) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.setActiveDeploymentTask = context -> manager().serviceClient().getApps() .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) .then(context.voidMono()); return this; } @Override public void beforeGroupCreateOrUpdate() { if (setActiveDeploymentTask != null) { this.addPostRunDependent(setActiveDeploymentTask); } setActiveDeploymentTask = null; } @Override public Mono<SpringApp> createResourceAsync() { if (springAppDeploymentToCreate == null) { withDefaultActiveDeployment(); } return manager().serviceClient().getApps().createOrUpdateAsync( parent().resourceGroupName(), parent().name(), name(), new AppResourceInner()) .thenMany(springAppDeploymentToCreate.createAsync()) .then(updateResourceAsync()); } @Override public Mono<SpringApp> updateResourceAsync() { return manager().serviceClient().getApps().updateAsync( parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; }); } @Override public Mono<Void> deleteResourceAsync() { return manager().serviceClient().getApps().deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono<AppResourceInner> getInnerAsync() { return manager().serviceClient().getApps().getAsync(parent().resourceGroupName(), parent().name(), name()); } @Override public String id() { return innerModel().id(); } @Override public SpringAppImpl update() { prepareUpdate(); return this; } public AppPlatformManager manager() { return parent().manager(); } @Override public SpringAppImpl withServiceBinding(String name, BindingResourceProperties bindingProperties) { serviceBindings.prepareCreateOrUpdate(name, bindingProperties); return this; } @Override public SpringAppImpl withoutServiceBinding(String name) { serviceBindings.prepareDelete(name); return this; } @Override public SpringAppImpl withDefaultActiveDeployment() { String defaultDeploymentName = "default"; withActiveDeployment(defaultDeploymentName); springAppDeploymentToCreate = deployments().define(defaultDeploymentName) .withExistingSource(UserSourceType.JAR, String.format("<%s>", defaultDeploymentName)); return this; } @Override @SuppressWarnings("unchecked") public <T extends SpringAppDeployment.DefinitionStages.WithAttach<? extends SpringApp.DefinitionStages.WithCreate, T>> SpringAppDeployment.DefinitionStages.Blank<T> defineActiveDeployment(String name) { return (SpringAppDeployment.DefinitionStages.Blank<T>) deployments.define(name); } SpringAppImpl addActiveDeployment(SpringAppDeploymentImpl deployment) { withActiveDeployment(deployment.name()); springAppDeploymentToCreate = deployment; return this; } @Override public SpringAppImpl withConfigurationServiceBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService != null) { Map<String, Object> configurationServiceConfigs = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, configurationService.id()); } return this; } @Override public SpringAppImpl withoutConfigurationServiceBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } @Override public SpringAppImpl withServiceRegistryBinding() { ensureProperty(); Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { addonConfigs = new HashMap<>(); innerModel().properties().withAddonConfigs(addonConfigs); } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry != null) { Map<String, Object> serviceRegistryConfigs = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); serviceRegistryConfigs.put(Constants.BINDING_RESOURCE_ID, serviceRegistry.id()); } return this; } @Override public SpringAppImpl withoutServiceRegistryBinding() { if (innerModel().properties() == null) { return this; } Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs(); if (addonConfigs == null) { return this; } Map<String, Object> configurationServiceConfigs = addonConfigs.get(Constants.SERVICE_REGISTRY_KEY); if (configurationServiceConfigs == null) { return this; } configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, ""); return this; } }
Basically all 4 changes are: Merge azure-core Context and reactor Context, when sending the request. Rest is only difference of indent.
public Mono<PollResponse<T>> poll(PollingContext<T> pollingContext, TypeReference<T> pollResponseType) { HttpRequest request = new HttpRequest(HttpMethod.GET, pollingContext.getData(PollingConstants.LOCATION)); return FluxUtil.withContext(context1 -> httpPipeline.send(request, CoreUtils.mergeContexts(context1, this.context))) .flatMap(response -> { HttpHeader locationHeader = response.getHeaders().get(PollingConstants.LOCATION); if (locationHeader != null) { pollingContext.setData(PollingConstants.LOCATION, locationHeader.getValue()); } LongRunningOperationStatus status; if (response.getStatusCode() == 202) { status = LongRunningOperationStatus.IN_PROGRESS; } else if (response.getStatusCode() >= 200 && response.getStatusCode() <= 204) { status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else { status = LongRunningOperationStatus.FAILED; } return response.getBodyAsByteArray().map(BinaryData::fromBytes).flatMap(binaryData -> { pollingContext.setData(PollingConstants.POLL_RESPONSE_BODY, binaryData.toString()); Duration retryAfter = ImplUtils.getRetryAfterFromHeaders(response.getHeaders(), OffsetDateTime::now); return PollingUtils.deserializeResponse(binaryData, serializer, pollResponseType) .map(value -> new PollResponse<>(status, value, retryAfter)); }); }); }
CoreUtils.mergeContexts(context1, this.context)))
new HttpRequest(HttpMethod.GET, pollingContext.getData(PollingConstants.LOCATION)); return FluxUtil.withContext(context1 -> httpPipeline.send(request, CoreUtils.mergeContexts(context1, this.context))) .flatMap(response -> { HttpHeader locationHeader = response.getHeaders().get(PollingConstants.LOCATION); if (locationHeader != null) { pollingContext.setData(PollingConstants.LOCATION, locationHeader.getValue()); } LongRunningOperationStatus status; if (response.getStatusCode() == 202) { status = LongRunningOperationStatus.IN_PROGRESS; } else if (response.getStatusCode() >= 200 && response.getStatusCode() <= 204) { status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else { status = LongRunningOperationStatus.FAILED; } return response.getBodyAsByteArray().map(BinaryData::fromBytes).flatMap(binaryData -> { pollingContext.setData(PollingConstants.POLL_RESPONSE_BODY, binaryData.toString()); Duration retryAfter = ImplUtils.getRetryAfterFromHeaders(response.getHeaders(), OffsetDateTime::now); return PollingUtils.deserializeResponse(binaryData, serializer, pollResponseType) .map(value -> new PollResponse<>(status, value, retryAfter)); }); }
class LocationPollingStrategy<T, U> implements PollingStrategy<T, U> { private static final ObjectSerializer DEFAULT_SERIALIZER = new DefaultJsonSerializer(); private static final ClientLogger LOGGER = new ClientLogger(LocationPollingStrategy.class); private final HttpPipeline httpPipeline; private final ObjectSerializer serializer; private final Context context; /** * Creates an instance of the location polling strategy using a JSON serializer. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @throws NullPointerException If {@code httpPipeline} is null. */ public LocationPollingStrategy(HttpPipeline httpPipeline) { this(httpPipeline, DEFAULT_SERIALIZER, Context.NONE); } /** * Creates an instance of the location polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @param serializer a custom serializer for serializing and deserializing polling responses * @throws NullPointerException If {@code httpPipeline} is null. */ public LocationPollingStrategy(HttpPipeline httpPipeline, ObjectSerializer serializer) { this(httpPipeline, serializer, Context.NONE); } /** * Creates an instance of the location polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @param serializer a custom serializer for serializing and deserializing polling responses * @param context an instance of {@link Context} * @throws NullPointerException If {@code httpPipeline} is null. */ public LocationPollingStrategy(HttpPipeline httpPipeline, ObjectSerializer serializer, Context context) { this.httpPipeline = Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null"); this.serializer = (serializer == null) ? DEFAULT_SERIALIZER : serializer; this.context = context == null ? Context.NONE : context; } @Override public Mono<Boolean> canPoll(Response<?> initialResponse) { HttpHeader locationHeader = initialResponse.getHeaders().get(PollingConstants.LOCATION); if (locationHeader != null) { try { new URL(locationHeader.getValue()); return Mono.just(true); } catch (MalformedURLException e) { LOGGER.info("Failed to parse Location header into a URL.", e); return Mono.just(false); } } return Mono.just(false); } @Override public Mono<PollResponse<T>> onInitialResponse(Response<?> response, PollingContext<T> pollingContext, TypeReference<T> pollResponseType) { HttpHeader locationHeader = response.getHeaders().get(PollingConstants.LOCATION); if (locationHeader != null) { pollingContext.setData(PollingConstants.LOCATION, locationHeader.getValue()); } pollingContext.setData(PollingConstants.HTTP_METHOD, response.getRequest().getHttpMethod().name()); pollingContext.setData(PollingConstants.REQUEST_URL, response.getRequest().getUrl().toString()); if (response.getStatusCode() == 200 || response.getStatusCode() == 201 || response.getStatusCode() == 202 || response.getStatusCode() == 204) { String retryAfterValue = response.getHeaders().getValue(PollingConstants.RETRY_AFTER); Duration retryAfter = retryAfterValue == null ? null : Duration.ofSeconds(Long.parseLong(retryAfterValue)); return PollingUtils.convertResponse(response.getValue(), serializer, pollResponseType) .map(value -> new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, value, retryAfter)) .switchIfEmpty(Mono.fromSupplier(() -> new PollResponse<>( LongRunningOperationStatus.IN_PROGRESS, null, retryAfter))); } else { return Mono.error(new AzureException(String.format("Operation failed or cancelled with status code %d," + ", 'Location' header: %s, and response body: %s", response.getStatusCode(), locationHeader, PollingUtils.serializeResponse(response.getValue(), serializer)))); } } @Override public Mono<PollResponse<T>> poll(PollingContext<T> pollingContext, TypeReference<T> pollResponseType) { HttpRequest request = ); } @Override public Mono<U> getResult(PollingContext<T> pollingContext, TypeReference<U> resultType) { if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.FAILED) { return Mono.error(new AzureException("Long running operation failed.")); } else if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.USER_CANCELLED) { return Mono.error(new AzureException("Long running operation cancelled.")); } String finalGetUrl; String httpMethod = pollingContext.getData(PollingConstants.HTTP_METHOD); if (HttpMethod.PUT.name().equalsIgnoreCase(httpMethod) || HttpMethod.PATCH.name().equalsIgnoreCase(httpMethod)) { finalGetUrl = pollingContext.getData(PollingConstants.REQUEST_URL); } else if (HttpMethod.POST.name().equalsIgnoreCase(httpMethod) && pollingContext.getData(PollingConstants.LOCATION) != null) { finalGetUrl = pollingContext.getData(PollingConstants.LOCATION); } else { return Mono.error(new AzureException("Cannot get final result")); } if (finalGetUrl == null) { String latestResponseBody = pollingContext.getData(PollingConstants.POLL_RESPONSE_BODY); return PollingUtils.deserializeResponse(BinaryData.fromString(latestResponseBody), serializer, resultType); } else { HttpRequest request = new HttpRequest(HttpMethod.GET, finalGetUrl); return FluxUtil.withContext(context1 -> httpPipeline.send(request, CoreUtils.mergeContexts(context1, this.context))) .flatMap(HttpResponse::getBodyAsByteArray) .map(BinaryData::fromBytes) .flatMap(binaryData -> PollingUtils.deserializeResponse(binaryData, serializer, resultType)); } } }
class LocationPollingStrategy<T, U> implements PollingStrategy<T, U> { private static final ObjectSerializer DEFAULT_SERIALIZER = new DefaultJsonSerializer(); private static final ClientLogger LOGGER = new ClientLogger(LocationPollingStrategy.class); private final HttpPipeline httpPipeline; private final ObjectSerializer serializer; private final Context context; /** * Creates an instance of the location polling strategy using a JSON serializer. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @throws NullPointerException If {@code httpPipeline} is null. */ public LocationPollingStrategy(HttpPipeline httpPipeline) { this(httpPipeline, DEFAULT_SERIALIZER, Context.NONE); } /** * Creates an instance of the location polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @param serializer a custom serializer for serializing and deserializing polling responses * @throws NullPointerException If {@code httpPipeline} is null. */ public LocationPollingStrategy(HttpPipeline httpPipeline, ObjectSerializer serializer) { this(httpPipeline, serializer, Context.NONE); } /** * Creates an instance of the location polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @param serializer a custom serializer for serializing and deserializing polling responses * @param context an instance of {@link Context} * @throws NullPointerException If {@code httpPipeline} is null. */ public LocationPollingStrategy(HttpPipeline httpPipeline, ObjectSerializer serializer, Context context) { this.httpPipeline = Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null"); this.serializer = (serializer == null) ? DEFAULT_SERIALIZER : serializer; this.context = context == null ? Context.NONE : context; } @Override public Mono<Boolean> canPoll(Response<?> initialResponse) { HttpHeader locationHeader = initialResponse.getHeaders().get(PollingConstants.LOCATION); if (locationHeader != null) { try { new URL(locationHeader.getValue()); return Mono.just(true); } catch (MalformedURLException e) { LOGGER.info("Failed to parse Location header into a URL.", e); return Mono.just(false); } } return Mono.just(false); } @Override public Mono<PollResponse<T>> onInitialResponse(Response<?> response, PollingContext<T> pollingContext, TypeReference<T> pollResponseType) { HttpHeader locationHeader = response.getHeaders().get(PollingConstants.LOCATION); if (locationHeader != null) { pollingContext.setData(PollingConstants.LOCATION, locationHeader.getValue()); } pollingContext.setData(PollingConstants.HTTP_METHOD, response.getRequest().getHttpMethod().name()); pollingContext.setData(PollingConstants.REQUEST_URL, response.getRequest().getUrl().toString()); if (response.getStatusCode() == 200 || response.getStatusCode() == 201 || response.getStatusCode() == 202 || response.getStatusCode() == 204) { String retryAfterValue = response.getHeaders().getValue(PollingConstants.RETRY_AFTER); Duration retryAfter = retryAfterValue == null ? null : Duration.ofSeconds(Long.parseLong(retryAfterValue)); return PollingUtils.convertResponse(response.getValue(), serializer, pollResponseType) .map(value -> new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, value, retryAfter)) .switchIfEmpty(Mono.fromSupplier(() -> new PollResponse<>( LongRunningOperationStatus.IN_PROGRESS, null, retryAfter))); } else { return Mono.error(new AzureException(String.format("Operation failed or cancelled with status code %d," + ", 'Location' header: %s, and response body: %s", response.getStatusCode(), locationHeader, PollingUtils.serializeResponse(response.getValue(), serializer)))); } } @Override public Mono<PollResponse<T>> poll(PollingContext<T> pollingContext, TypeReference<T> pollResponseType) { HttpRequest request = ); } @Override public Mono<U> getResult(PollingContext<T> pollingContext, TypeReference<U> resultType) { if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.FAILED) { return Mono.error(new AzureException("Long running operation failed.")); } else if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.USER_CANCELLED) { return Mono.error(new AzureException("Long running operation cancelled.")); } String finalGetUrl; String httpMethod = pollingContext.getData(PollingConstants.HTTP_METHOD); if (HttpMethod.PUT.name().equalsIgnoreCase(httpMethod) || HttpMethod.PATCH.name().equalsIgnoreCase(httpMethod)) { finalGetUrl = pollingContext.getData(PollingConstants.REQUEST_URL); } else if (HttpMethod.POST.name().equalsIgnoreCase(httpMethod) && pollingContext.getData(PollingConstants.LOCATION) != null) { finalGetUrl = pollingContext.getData(PollingConstants.LOCATION); } else { return Mono.error(new AzureException("Cannot get final result")); } if (finalGetUrl == null) { String latestResponseBody = pollingContext.getData(PollingConstants.POLL_RESPONSE_BODY); return PollingUtils.deserializeResponse(BinaryData.fromString(latestResponseBody), serializer, resultType); } else { HttpRequest request = new HttpRequest(HttpMethod.GET, finalGetUrl); return FluxUtil.withContext(context1 -> httpPipeline.send(request, CoreUtils.mergeContexts(context1, this.context))) .flatMap(HttpResponse::getBodyAsByteArray) .map(BinaryData::fromBytes) .flatMap(binaryData -> PollingUtils.deserializeResponse(binaryData, serializer, resultType)); } } }
Any reason for this change?
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString();
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
Mind adding a comment here stating that this is done to ensure the class has been loading, triggering the static initializer to bind the accessor, and without this a NullPointerException could occur.
private static void ensureAccessorSet() { if (accessor == null) { BinaryData.fromString(""); } }
if (accessor == null) {
private static void ensureAccessorSet() { if (accessor == null) { BinaryData.fromString(""); } }
class BinaryDataHelper { private static BinaryDataAccessor accessor; /** * Type defining the methods that access private values of {@link BinaryData}. */ public interface BinaryDataAccessor { /** * Creates a new {@link BinaryData} with the given content. * * @param content The {@link BinaryDataContent}. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code content} is null. */ BinaryData createBinaryData(BinaryDataContent content); /** * Gets the {@link BinaryDataContent} that backs the {@link BinaryData}. * * @param binaryData The {@link BinaryData} having its content retrieved. * @return The {@link BinaryDataContent} that backs the {@link BinaryData}. */ BinaryDataContent getContent(BinaryData binaryData); } /** * The method called from {@link BinaryData} to set its accessor. * * @param binaryDataAccessor The accessor. */ public static void setAccessor(final BinaryDataAccessor binaryDataAccessor) { accessor = binaryDataAccessor; } /** * Creates a new {@link BinaryData} with the given content. * * @param content The {@link BinaryDataContent}. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code content} is null. */ public static BinaryData createBinaryData(BinaryDataContent content) { ensureAccessorSet(); return accessor.createBinaryData(content); } /** * Gets the {@link BinaryDataContent} that backs the {@link BinaryData}. * * @param binaryData The {@link BinaryData} having its content retrieved. * @return The {@link BinaryDataContent} that backs the {@link BinaryData}. */ public static BinaryDataContent getContent(BinaryData binaryData) { ensureAccessorSet(); return accessor.getContent(binaryData); } }
class BinaryDataHelper { private static BinaryDataAccessor accessor; /** * Type defining the methods that access private values of {@link BinaryData}. */ public interface BinaryDataAccessor { /** * Creates a new {@link BinaryData} with the given content. * * @param content The {@link BinaryDataContent}. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code content} is null. */ BinaryData createBinaryData(BinaryDataContent content); /** * Gets the {@link BinaryDataContent} that backs the {@link BinaryData}. * * @param binaryData The {@link BinaryData} having its content retrieved. * @return The {@link BinaryDataContent} that backs the {@link BinaryData}. */ BinaryDataContent getContent(BinaryData binaryData); } /** * The method called from {@link BinaryData} to set its accessor. * * @param binaryDataAccessor The accessor. */ public static void setAccessor(final BinaryDataAccessor binaryDataAccessor) { accessor = binaryDataAccessor; } /** * Creates a new {@link BinaryData} with the given content. * * @param content The {@link BinaryDataContent}. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code content} is null. */ public static BinaryData createBinaryData(BinaryDataContent content) { ensureAccessorSet(); return accessor.createBinaryData(content); } /** * Gets the {@link BinaryDataContent} that backs the {@link BinaryData}. * * @param binaryData The {@link BinaryData} having its content retrieved. * @return The {@link BinaryDataContent} that backs the {@link BinaryData}. */ public static BinaryDataContent getContent(BinaryData binaryData) { ensureAccessorSet(); return accessor.getContent(binaryData); } /** * The success of setting up accessor depends on the order in which classes are loaded. * This method ensures that if accessor hasn't been set we force-load BinaryData class * which in turns populates the accessor. */ }
Some binary data contents serve read-only buffers. ``` java.nio.ReadOnlyBufferException at java.base/java.nio.ByteBuffer.array(ByteBuffer.java:1051) at com.azure.communication.sms@1.2.0-beta.1/com.azure.communication.sms.SmsClientTests.checkForRepeatabilityOptions(SmsClientTests.java:176) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ```
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString();
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
Would a better option be `response.getRequest().getBodyAsBinaryData().toString()`?
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString();
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
Good idea but that'd require switching them to unreleased core. Not worth it in this PR imo - I'd rather start an GH issue with follow-ups that we have to do when this ships.
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString();
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
https://github.com/Azure/azure-sdk-for-java/issues/28796
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString();
public void checkForRepeatabilityOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "checkForRepeatabilityOptions"); Response<Iterable<SmsSendResult>> response = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE); String bodyRequest = StandardCharsets.UTF_8.decode(response.getRequest().getBody().blockLast()).toString(); assertTrue(bodyRequest.contains("repeatabilityRequestId")); assertTrue(bodyRequest.contains("repeatabilityFirstSent")); }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
class SmsClientTests extends SmsTestBase { private SmsClient client; @Override protected void beforeTest() { super.beforeTest(); assumeTrue(shouldEnableSmsTests()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingConnectionString(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsUsingTokenCredential(HttpClient httpClient) { TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential); client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroup(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupSync"); Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE); for (SmsSendResult result : sendResults) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToGroupWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE); for (SmsSendResult result : sendResults.getValue()) { assertHappyPath(result); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync"); SmsSendOptions options = new SmsSendOptions(); options.setDeliveryReportEnabled(true); options.setTag("New Tag"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options); assertHappyPath(sendResult); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromFakeNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromFakeNumberSync"); try { client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendFromUnauthorizedNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync"); try { SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE); } catch (Exception exception) { assertNotNull(((HttpResponseException) exception).getResponse().getStatusCode()); assertEquals(401, ((HttpResponseException) exception).getResponse().getStatusCode()); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendToFakePhoneNumber(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendToFakePhoneNumberSync"); SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE); assertFalse(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 400); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void sendTwoMessages(HttpClient httpClient) { SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient); client = setupSyncClient(builder, "sendTwoMessagesSync"); SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE); assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId()); assertHappyPath(firstResponse); assertHappyPath(secondResponse); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private void assertHappyPath(SmsSendResult sendResult) { assertTrue(sendResult.isSuccessful()); assertEquals(sendResult.getHttpStatusCode(), 202); assertNotNull(sendResult.getMessageId()); } }
I added javadocs to the method.
private static void ensureAccessorSet() { if (accessor == null) { BinaryData.fromString(""); } }
if (accessor == null) {
private static void ensureAccessorSet() { if (accessor == null) { BinaryData.fromString(""); } }
class BinaryDataHelper { private static BinaryDataAccessor accessor; /** * Type defining the methods that access private values of {@link BinaryData}. */ public interface BinaryDataAccessor { /** * Creates a new {@link BinaryData} with the given content. * * @param content The {@link BinaryDataContent}. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code content} is null. */ BinaryData createBinaryData(BinaryDataContent content); /** * Gets the {@link BinaryDataContent} that backs the {@link BinaryData}. * * @param binaryData The {@link BinaryData} having its content retrieved. * @return The {@link BinaryDataContent} that backs the {@link BinaryData}. */ BinaryDataContent getContent(BinaryData binaryData); } /** * The method called from {@link BinaryData} to set its accessor. * * @param binaryDataAccessor The accessor. */ public static void setAccessor(final BinaryDataAccessor binaryDataAccessor) { accessor = binaryDataAccessor; } /** * Creates a new {@link BinaryData} with the given content. * * @param content The {@link BinaryDataContent}. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code content} is null. */ public static BinaryData createBinaryData(BinaryDataContent content) { ensureAccessorSet(); return accessor.createBinaryData(content); } /** * Gets the {@link BinaryDataContent} that backs the {@link BinaryData}. * * @param binaryData The {@link BinaryData} having its content retrieved. * @return The {@link BinaryDataContent} that backs the {@link BinaryData}. */ public static BinaryDataContent getContent(BinaryData binaryData) { ensureAccessorSet(); return accessor.getContent(binaryData); } }
class BinaryDataHelper { private static BinaryDataAccessor accessor; /** * Type defining the methods that access private values of {@link BinaryData}. */ public interface BinaryDataAccessor { /** * Creates a new {@link BinaryData} with the given content. * * @param content The {@link BinaryDataContent}. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code content} is null. */ BinaryData createBinaryData(BinaryDataContent content); /** * Gets the {@link BinaryDataContent} that backs the {@link BinaryData}. * * @param binaryData The {@link BinaryData} having its content retrieved. * @return The {@link BinaryDataContent} that backs the {@link BinaryData}. */ BinaryDataContent getContent(BinaryData binaryData); } /** * The method called from {@link BinaryData} to set its accessor. * * @param binaryDataAccessor The accessor. */ public static void setAccessor(final BinaryDataAccessor binaryDataAccessor) { accessor = binaryDataAccessor; } /** * Creates a new {@link BinaryData} with the given content. * * @param content The {@link BinaryDataContent}. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code content} is null. */ public static BinaryData createBinaryData(BinaryDataContent content) { ensureAccessorSet(); return accessor.createBinaryData(content); } /** * Gets the {@link BinaryDataContent} that backs the {@link BinaryData}. * * @param binaryData The {@link BinaryData} having its content retrieved. * @return The {@link BinaryDataContent} that backs the {@link BinaryData}. */ public static BinaryDataContent getContent(BinaryData binaryData) { ensureAccessorSet(); return accessor.getContent(binaryData); } /** * The success of setting up accessor depends on the order in which classes are loaded. * This method ensures that if accessor hasn't been set we force-load BinaryData class * which in turns populates the accessor. */ }
nit: ```suggestion return monoError(LOGGER, new NullPointerException("'data' cannot be null.")); ```
public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data, Long length, boolean bufferContent) { if (data == null) { return monoError(LOGGER, new NullPointerException("'content' cannot be null.")); } if (length != null && length < 0) { return monoError(LOGGER, new IllegalArgumentException("'length' cannot be less than 0.")); } if (bufferContent && length != null && length > MAX_ARRAY_SIZE) { return monoError(LOGGER, new IllegalArgumentException( String.format("'length' cannot be greater than %d when content buffering is enabled.", MAX_ARRAY_SIZE))); } if (bufferContent) { if (length != null) { return FluxUtil.collectBytesInByteBufferStream(data, length.intValue()) .flatMap(bytes -> Mono.just(BinaryData.fromBytes(bytes))); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(BinaryData.fromBytes(bytes))); } else { return Mono.just(new BinaryData(new FluxByteBufferContent(data, length))); } }
return monoError(LOGGER, new NullPointerException("'content' cannot be null."));
public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data, Long length, boolean bufferContent) { if (data == null) { return monoError(LOGGER, new NullPointerException("'data' cannot be null.")); } if (length != null && length < 0) { return monoError(LOGGER, new IllegalArgumentException("'length' cannot be less than 0.")); } if (bufferContent && length != null && length > MAX_ARRAY_SIZE) { return monoError(LOGGER, new IllegalArgumentException( String.format("'length' cannot be greater than %d when content buffering is enabled.", MAX_ARRAY_SIZE))); } if (bufferContent) { if (length != null) { return FluxUtil.collectBytesInByteBufferStream(data, length.intValue()) .flatMap(bytes -> Mono.just(BinaryData.fromBytes(bytes))); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(BinaryData.fromBytes(bytes))); } else { return Mono.just(new BinaryData(new FluxByteBufferContent(data, length))); } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); static final JsonSerializer SERIALIZER = JsonSerializerProviders.createInstance(true); static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private final BinaryDataContent content; BinaryData(BinaryDataContent content) { this.content = Objects.requireNonNull(content, "'content' cannot be null."); } static { BinaryDataHelper.setAccessor(new BinaryDataHelper.BinaryDataAccessor() { @Override public BinaryData createBinaryData(BinaryDataContent content) { return new BinaryData(content); } @Override public BinaryDataContent getContent(BinaryData binaryData) { return binaryData.content; } }); } /** * Creates an instance of {@link BinaryData} from the given {@link InputStream}. Depending on the type of * inputStream, the BinaryData instance created may or may not allow reading the content more than once. The * stream content is not cached if the stream is not read into a format that requires the content to be fully read * into memory. * <p> * <b>NOTE:</b> The {@link InputStream} is not closed by this function. * </p> * * <p><strong>Create an instance from an InputStream</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromStream * <pre> * final ByteArrayInputStream inputStream = new ByteArrayInputStream& * BinaryData binaryData = BinaryData.fromStream& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromStream * * @param inputStream The {@link InputStream} that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the {@link InputStream}. * @throws UncheckedIOException If any error happens while reading the {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. */ public static BinaryData fromStream(InputStream inputStream) { return new BinaryData(new InputStreamContent(inputStream)); } /** * Creates an instance of {@link BinaryData} from the given {@link InputStream}. * <b>NOTE:</b> The {@link InputStream} is not closed by this function. * * <p><strong>Create an instance from an InputStream</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromStreamAsync * <pre> * final ByteArrayInputStream inputStream = new ByteArrayInputStream& * * Mono&lt;BinaryData&gt; binaryDataMono = BinaryData.fromStreamAsync& * * Disposable subscriber = binaryDataMono * .map& * System.out.println& * return true; * & * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromStreamAsync * * @param inputStream The {@link InputStream} that {@link BinaryData} will represent. * @return A {@link Mono} of {@link BinaryData} representing the {@link InputStream}. * @throws UncheckedIOException If any error happens while reading the {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}. * * <p><strong>Create an instance from a Flux of ByteBuffer</strong></p> * * <p>This method aggregates data into single byte array.</p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFlux * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * final Flux&lt;ByteBuffer&gt; dataFlux = Flux.just& * * Mono&lt;BinaryData&gt; binaryDataMono = BinaryData.fromFlux& * * Disposable subscriber = binaryDataMono * .map& * System.out.println& * return true; * & * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFlux * * @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent. * @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}. * @throws NullPointerException If {@code data} is null. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { return fromFlux(data, null); } /** * Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}. * * <p><strong>Create an instance from a Flux of ByteBuffer</strong></p> * * <p>This method aggregates data into single byte array.</p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFlux * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * final long length = data.length; * final Flux&lt;ByteBuffer&gt; dataFlux = Flux.just& * * Mono&lt;BinaryData&gt; binaryDataMono = BinaryData.fromFlux& * * Disposable subscriber = binaryDataMono * .map& * System.out.println& * return true; * & * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFlux * * @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent. * @param length The length of {@code data} in bytes. * @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}. * @throws IllegalArgumentException if the length is less than zero. * @throws NullPointerException if {@code data} is null. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data, Long length) { return fromFlux(data, length, true); } /** * Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}. * * <p><strong>Create an instance from a Flux of ByteBuffer</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFlux * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * final long length = data.length; * final boolean shouldAggregateData = false; * final Flux&lt;ByteBuffer&gt; dataFlux = Flux.just& * * Mono&lt;BinaryData&gt; binaryDataMono = BinaryData.fromFlux& * * Disposable subscriber = binaryDataMono * .map& * System.out.println& * return true; * & * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFlux * * @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent. * @param length The length of {@code data} in bytes. * @param bufferContent A flag indicating whether {@link Flux} should be buffered eagerly or * consumption deferred. * @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}. * @throws IllegalArgumentException if the length is less than zero. * @throws NullPointerException if {@code data} is null. */ /** * Creates an instance of {@link BinaryData} from the given {@link String}. * <p> * The {@link String} is converted into bytes using {@link String * StandardCharsets * </p> * <p><strong>Create an instance from a String</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromString * <pre> * final String data = &quot;Some Data&quot;; * & * BinaryData binaryData = BinaryData.fromString& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromString * * @param data The {@link String} that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the {@link String}. * @throws NullPointerException If {@code data} is null. */ public static BinaryData fromString(String data) { return new BinaryData(new StringContent(data)); } /** * Creates an instance of {@link BinaryData} from the given byte array. * <p> * If the byte array is null or zero length an empty {@link BinaryData} will be returned. Note that the input * byte array is used as a reference by this instance of {@link BinaryData} and any changes to the byte array * outside of this instance will result in the contents of this BinaryData instance being updated as well. To * safely update the byte array without impacting the BinaryData instance, perform an array copy first. * </p> * * <p><strong>Create an instance from a byte array</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromBytes * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * BinaryData binaryData = BinaryData.fromBytes& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromBytes * * @param data The byte array that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the byte array. * @throws NullPointerException If {@code data} is null. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(new ByteArrayContent(data)); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link * JsonSerializer}. * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to serialize the object. *</p> * <p><strong>Creating an instance from an Object</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * BinaryData binaryData = BinaryData.fromObject& * * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromObject * * @param data The object that will be JSON serialized that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the JSON serialized object. * @throws NullPointerException If {@code data} is null. * @see JsonSerializer */ public static BinaryData fromObject(Object data) { return fromObject(data, SERIALIZER); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link * JsonSerializer}. * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to serialize the object. * </p> * <p><strong>Creating an instance from an Object</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * Disposable subscriber = BinaryData.fromObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromObjectAsync * * @param data The object that will be JSON serialized that {@link BinaryData} will represent. * @return A {@link Mono} of {@link BinaryData} representing the JSON serialized object. * @see JsonSerializer */ public static Mono<BinaryData> fromObjectAsync(Object data) { return fromObjectAsync(data, SERIALIZER); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link * ObjectSerializer}. * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * </p> * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Create an instance from an Object</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromObject * * @param data The object that will be serialized that {@link BinaryData} will represent. The {@code serializer} * determines how {@code null} data is serialized. * @param serializer The {@link ObjectSerializer} used to serialize object. * @return A {@link BinaryData} representing the serialized object. * @throws NullPointerException If {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { return new BinaryData(new SerializableContent(data, serializer)); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link * ObjectSerializer}. * * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * </p> * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Create an instance from an Object</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * final ObjectSerializer serializer = * new MyJsonSerializer& * Disposable subscriber = BinaryData.fromObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromObjectAsync * * @param data The object that will be serialized that {@link BinaryData} will represent. The {@code serializer} * determines how {@code null} data is serialized. * @param serializer The {@link ObjectSerializer} used to serialize object. * @return A {@link Mono} of {@link BinaryData} representing the serialized object. * @throws NullPointerException If {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Creates a {@link BinaryData} that uses the content of the file at {@link Path} as its data. This method checks * for the existence of the file at the time of creating an instance of {@link BinaryData}. The file, however, is * not read until there is an attempt to read the contents of the returned BinaryData instance. * * <p><strong>Create an instance from a file</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFile --> * <pre> * BinaryData binaryData = BinaryData.fromFile& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFile --> * * @param file The {@link Path} that will be the {@link BinaryData} data. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code file} is null. */ public static BinaryData fromFile(Path file) { return fromFile(file, STREAM_READ_SIZE); } /** * Creates a {@link BinaryData} that uses the content of the file at {@link Path file} as its data. This method * checks for the existence of the file at the time of creating an instance of {@link BinaryData}. The file, * however, is not read until there is an attempt to read the contents of the returned BinaryData instance. * * <p><strong>Create an instance from a file</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFile * <pre> * BinaryData binaryData = BinaryData.fromFile& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFile * * @param file The {@link Path} that will be the {@link BinaryData} data. * @param chunkSize The requested size for each read of the path. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code file} is null. * @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code * length} is greater than the file size or {@code chunkSize} is less than or equal to 0. * @throws UncheckedIOException if the file does not exist. */ public static BinaryData fromFile(Path file, int chunkSize) { return new BinaryData(new FileContent(file, chunkSize)); } /** * Returns a byte array representation of this {@link BinaryData}. This method returns a reference to the * underlying byte array. Modifying the contents of the returned byte array will also change the content of this * BinaryData instance. If the content source of this BinaryData instance is a file, an Inputstream or a * {@code Flux<ByteBuffer>} the source is not modified. To safely update the byte array, it is recommended * to make a copy of the contents first. * * @return A byte array representing this {@link BinaryData}. */ public byte[] toBytes() { return content.toBytes(); } /** * Returns a {@link String} representation of this {@link BinaryData} by converting its data using the UTF-8 * character set. A new instance of String is created each time this method is called. * * @return A {@link String} representing this {@link BinaryData}. */ public String toString() { return content.toString(); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * & * & * * BinaryData binaryData = BinaryData.fromObject& * * Person person = binaryData.toObject& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * @param <T> Type of the deserialized Object. * @param clazz The {@link Class} representing the Object's type. * @return An {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} is null. * @see JsonSerializer */ public <T> T toObject(Class<T> clazz) { return toObject(TypeReference.createInstance(clazz), SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * & * & * * BinaryData binaryData = BinaryData.fromObject& * * Person person = binaryData.toObject& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * final Person person1 = new Person& * final Person person2 = new Person& * * List&lt;Person&gt; personList = new ArrayList&lt;&gt;& * personList.add& * personList.add& * * & * & * & * & * & * * * BinaryData binaryData = BinaryData.fromObject& * * List&lt;Person&gt; persons = binaryData.toObject& * persons.forEach& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * @param typeReference The {@link TypeReference} representing the Object's type. * @param <T> Type of the deserialized Object. * @return An {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} is null. * @see JsonSerializer */ public <T> T toObject(TypeReference<T> typeReference) { return toObject(typeReference, SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Person person = binaryData.toObject& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * @param clazz The {@link Class} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return An {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { return toObject(TypeReference.createInstance(clazz), serializer); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Person person = binaryData.toObject& * System.out.println& * * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * final Person person1 = new Person& * final Person person2 = new Person& * * List&lt;Person&gt; personList = new ArrayList&lt;&gt;& * personList.add& * personList.add& * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * & * List&lt;Person&gt; persons = binaryData.toObject& * persons.forEach& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * @param typeReference The {@link TypeReference} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return An {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer) { Objects.requireNonNull(typeReference, "'typeReference' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); return content.toObject(typeReference, serializer); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * & * & * * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData.toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * @param clazz The {@link Class} representing the Object's type. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} is null. * @see JsonSerializer */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { return toObjectAsync(TypeReference.createInstance(clazz), SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * & * & * * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData.toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * final Person person1 = new Person& * final Person person2 = new Person& * * List&lt;Person&gt; personList = new ArrayList&lt;&gt;& * personList.add& * personList.add& * * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData.toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * @param typeReference The {@link TypeReference} representing the Object's type. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} is null. * @see JsonSerializer */ public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference) { return toObjectAsync(typeReference, SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData.toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * @param clazz The {@link Class} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { return toObjectAsync(TypeReference.createInstance(clazz), serializer); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData * .toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * final Person person1 = new Person& * final Person person2 = new Person& * * List&lt;Person&gt; personList = new ArrayList&lt;&gt;& * personList.add& * personList.add& * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData * .toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * @param typeReference The {@link TypeReference} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference, ObjectSerializer serializer) { return Mono.fromCallable(() -> toObject(typeReference, serializer)); } /** * Returns an {@link InputStream} representation of this {@link BinaryData}. * * <p><strong>Get an InputStream from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toStream --> * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * BinaryData binaryData = BinaryData.fromStream& * final byte[] bytes = new byte[data.length]; * binaryData.toStream& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.toStream --> * * @return An {@link InputStream} representing the {@link BinaryData}. */ public InputStream toStream() { return content.toStream(); } /** * Returns a read-only {@link ByteBuffer} representation of this {@link BinaryData}. * <p> * Attempting to mutate the returned {@link ByteBuffer} will throw a {@link ReadOnlyBufferException}. * * <p><strong>Get a read-only ByteBuffer from the BinaryData</strong></p> * * <!-- src_embed com.azure.util.BinaryData.toByteBuffer --> * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * BinaryData binaryData = BinaryData.fromBytes& * final byte[] bytes = new byte[data.length]; * binaryData.toByteBuffer& * System.out.println& * </pre> * <!-- end com.azure.util.BinaryData.toByteBuffer --> * * @return A read-only {@link ByteBuffer} representing the {@link BinaryData}. */ public ByteBuffer toByteBuffer() { return content.toByteBuffer(); } /** * Returns the content of this {@link BinaryData} instance as a flux of {@link ByteBuffer ByteBuffers}. The * content is not read from the underlying data source until the {@link Flux} is subscribed to. * * @return the content of this {@link BinaryData} instance as a flux of {@link ByteBuffer ByteBuffers}. */ public Flux<ByteBuffer> toFluxByteBuffer() { return content.toFluxByteBuffer(); } /** * Returns the length of the content, if it is known. The length can be {@code null} if the source did not * specify the length or the length cannot be determined without reading the whole content. * * @return the length of the content, if it is known. */ public Long getLength() { return content.getLength(); } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); static final JsonSerializer SERIALIZER = JsonSerializerProviders.createInstance(true); static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private final BinaryDataContent content; BinaryData(BinaryDataContent content) { this.content = Objects.requireNonNull(content, "'content' cannot be null."); } static { BinaryDataHelper.setAccessor(new BinaryDataHelper.BinaryDataAccessor() { @Override public BinaryData createBinaryData(BinaryDataContent content) { return new BinaryData(content); } @Override public BinaryDataContent getContent(BinaryData binaryData) { return binaryData.content; } }); } /** * Creates an instance of {@link BinaryData} from the given {@link InputStream}. Depending on the type of * inputStream, the BinaryData instance created may or may not allow reading the content more than once. The * stream content is not cached if the stream is not read into a format that requires the content to be fully read * into memory. * <p> * <b>NOTE:</b> The {@link InputStream} is not closed by this function. * </p> * * <p><strong>Create an instance from an InputStream</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromStream * <pre> * final ByteArrayInputStream inputStream = new ByteArrayInputStream& * BinaryData binaryData = BinaryData.fromStream& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromStream * * @param inputStream The {@link InputStream} that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the {@link InputStream}. * @throws UncheckedIOException If any error happens while reading the {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. */ public static BinaryData fromStream(InputStream inputStream) { return new BinaryData(new InputStreamContent(inputStream)); } /** * Creates an instance of {@link BinaryData} from the given {@link InputStream}. * <b>NOTE:</b> The {@link InputStream} is not closed by this function. * * <p><strong>Create an instance from an InputStream</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromStreamAsync * <pre> * final ByteArrayInputStream inputStream = new ByteArrayInputStream& * * Mono&lt;BinaryData&gt; binaryDataMono = BinaryData.fromStreamAsync& * * Disposable subscriber = binaryDataMono * .map& * System.out.println& * return true; * & * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromStreamAsync * * @param inputStream The {@link InputStream} that {@link BinaryData} will represent. * @return A {@link Mono} of {@link BinaryData} representing the {@link InputStream}. * @throws UncheckedIOException If any error happens while reading the {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}. * * <p><strong>Create an instance from a Flux of ByteBuffer</strong></p> * * <p>This method aggregates data into single byte array.</p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFlux * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * final Flux&lt;ByteBuffer&gt; dataFlux = Flux.just& * * Mono&lt;BinaryData&gt; binaryDataMono = BinaryData.fromFlux& * * Disposable subscriber = binaryDataMono * .map& * System.out.println& * return true; * & * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFlux * * @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent. * @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}. * @throws NullPointerException If {@code data} is null. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { return fromFlux(data, null); } /** * Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}. * * <p><strong>Create an instance from a Flux of ByteBuffer</strong></p> * * <p>This method aggregates data into single byte array.</p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFlux * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * final long length = data.length; * final Flux&lt;ByteBuffer&gt; dataFlux = Flux.just& * * Mono&lt;BinaryData&gt; binaryDataMono = BinaryData.fromFlux& * * Disposable subscriber = binaryDataMono * .map& * System.out.println& * return true; * & * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFlux * * @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent. * @param length The length of {@code data} in bytes. * @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}. * @throws IllegalArgumentException if the length is less than zero. * @throws NullPointerException if {@code data} is null. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data, Long length) { return fromFlux(data, length, true); } /** * Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}. * * <p><strong>Create an instance from a Flux of ByteBuffer</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFlux * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * final long length = data.length; * final boolean shouldAggregateData = false; * final Flux&lt;ByteBuffer&gt; dataFlux = Flux.just& * * Mono&lt;BinaryData&gt; binaryDataMono = BinaryData.fromFlux& * * Disposable subscriber = binaryDataMono * .map& * System.out.println& * return true; * & * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFlux * * @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent. * @param length The length of {@code data} in bytes. * @param bufferContent A flag indicating whether {@link Flux} should be buffered eagerly or * consumption deferred. * @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}. * @throws IllegalArgumentException if the length is less than zero. * @throws NullPointerException if {@code data} is null. */ /** * Creates an instance of {@link BinaryData} from the given {@link String}. * <p> * The {@link String} is converted into bytes using {@link String * StandardCharsets * </p> * <p><strong>Create an instance from a String</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromString * <pre> * final String data = &quot;Some Data&quot;; * & * BinaryData binaryData = BinaryData.fromString& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromString * * @param data The {@link String} that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the {@link String}. * @throws NullPointerException If {@code data} is null. */ public static BinaryData fromString(String data) { return new BinaryData(new StringContent(data)); } /** * Creates an instance of {@link BinaryData} from the given byte array. * <p> * If the byte array is null or zero length an empty {@link BinaryData} will be returned. Note that the input * byte array is used as a reference by this instance of {@link BinaryData} and any changes to the byte array * outside of this instance will result in the contents of this BinaryData instance being updated as well. To * safely update the byte array without impacting the BinaryData instance, perform an array copy first. * </p> * * <p><strong>Create an instance from a byte array</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromBytes * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * BinaryData binaryData = BinaryData.fromBytes& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromBytes * * @param data The byte array that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the byte array. * @throws NullPointerException If {@code data} is null. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(new ByteArrayContent(data)); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link * JsonSerializer}. * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to serialize the object. *</p> * <p><strong>Creating an instance from an Object</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * BinaryData binaryData = BinaryData.fromObject& * * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromObject * * @param data The object that will be JSON serialized that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the JSON serialized object. * @throws NullPointerException If {@code data} is null. * @see JsonSerializer */ public static BinaryData fromObject(Object data) { return fromObject(data, SERIALIZER); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link * JsonSerializer}. * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to serialize the object. * </p> * <p><strong>Creating an instance from an Object</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * Disposable subscriber = BinaryData.fromObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromObjectAsync * * @param data The object that will be JSON serialized that {@link BinaryData} will represent. * @return A {@link Mono} of {@link BinaryData} representing the JSON serialized object. * @see JsonSerializer */ public static Mono<BinaryData> fromObjectAsync(Object data) { return fromObjectAsync(data, SERIALIZER); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link * ObjectSerializer}. * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * </p> * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Create an instance from an Object</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromObject * * @param data The object that will be serialized that {@link BinaryData} will represent. The {@code serializer} * determines how {@code null} data is serialized. * @param serializer The {@link ObjectSerializer} used to serialize object. * @return A {@link BinaryData} representing the serialized object. * @throws NullPointerException If {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { return new BinaryData(new SerializableContent(data, serializer)); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link * ObjectSerializer}. * * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * </p> * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Create an instance from an Object</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * final ObjectSerializer serializer = * new MyJsonSerializer& * Disposable subscriber = BinaryData.fromObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.fromObjectAsync * * @param data The object that will be serialized that {@link BinaryData} will represent. The {@code serializer} * determines how {@code null} data is serialized. * @param serializer The {@link ObjectSerializer} used to serialize object. * @return A {@link Mono} of {@link BinaryData} representing the serialized object. * @throws NullPointerException If {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Creates a {@link BinaryData} that uses the content of the file at {@link Path} as its data. This method checks * for the existence of the file at the time of creating an instance of {@link BinaryData}. The file, however, is * not read until there is an attempt to read the contents of the returned BinaryData instance. * * <p><strong>Create an instance from a file</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFile --> * <pre> * BinaryData binaryData = BinaryData.fromFile& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFile --> * * @param file The {@link Path} that will be the {@link BinaryData} data. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code file} is null. */ public static BinaryData fromFile(Path file) { return fromFile(file, STREAM_READ_SIZE); } /** * Creates a {@link BinaryData} that uses the content of the file at {@link Path file} as its data. This method * checks for the existence of the file at the time of creating an instance of {@link BinaryData}. The file, * however, is not read until there is an attempt to read the contents of the returned BinaryData instance. * * <p><strong>Create an instance from a file</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.fromFile * <pre> * BinaryData binaryData = BinaryData.fromFile& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.fromFile * * @param file The {@link Path} that will be the {@link BinaryData} data. * @param chunkSize The requested size for each read of the path. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code file} is null. * @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code * length} is greater than the file size or {@code chunkSize} is less than or equal to 0. * @throws UncheckedIOException if the file does not exist. */ public static BinaryData fromFile(Path file, int chunkSize) { return new BinaryData(new FileContent(file, chunkSize)); } /** * Returns a byte array representation of this {@link BinaryData}. This method returns a reference to the * underlying byte array. Modifying the contents of the returned byte array will also change the content of this * BinaryData instance. If the content source of this BinaryData instance is a file, an Inputstream or a * {@code Flux<ByteBuffer>} the source is not modified. To safely update the byte array, it is recommended * to make a copy of the contents first. * * @return A byte array representing this {@link BinaryData}. */ public byte[] toBytes() { return content.toBytes(); } /** * Returns a {@link String} representation of this {@link BinaryData} by converting its data using the UTF-8 * character set. A new instance of String is created each time this method is called. * * @return A {@link String} representing this {@link BinaryData}. */ public String toString() { return content.toString(); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * & * & * * BinaryData binaryData = BinaryData.fromObject& * * Person person = binaryData.toObject& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * @param <T> Type of the deserialized Object. * @param clazz The {@link Class} representing the Object's type. * @return An {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} is null. * @see JsonSerializer */ public <T> T toObject(Class<T> clazz) { return toObject(TypeReference.createInstance(clazz), SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * & * & * * BinaryData binaryData = BinaryData.fromObject& * * Person person = binaryData.toObject& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * final Person person1 = new Person& * final Person person2 = new Person& * * List&lt;Person&gt; personList = new ArrayList&lt;&gt;& * personList.add& * personList.add& * * & * & * & * & * & * * * BinaryData binaryData = BinaryData.fromObject& * * List&lt;Person&gt; persons = binaryData.toObject& * persons.forEach& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * @param typeReference The {@link TypeReference} representing the Object's type. * @param <T> Type of the deserialized Object. * @return An {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} is null. * @see JsonSerializer */ public <T> T toObject(TypeReference<T> typeReference) { return toObject(typeReference, SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Person person = binaryData.toObject& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * @param clazz The {@link Class} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return An {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { return toObject(TypeReference.createInstance(clazz), serializer); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Person person = binaryData.toObject& * System.out.println& * * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObject * <pre> * final Person person1 = new Person& * final Person person2 = new Person& * * List&lt;Person&gt; personList = new ArrayList&lt;&gt;& * personList.add& * personList.add& * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * & * List&lt;Person&gt; persons = binaryData.toObject& * persons.forEach& * </pre> * <!-- end com.azure.core.util.BinaryData.toObject * * @param typeReference The {@link TypeReference} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return An {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer) { Objects.requireNonNull(typeReference, "'typeReference' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); return content.toObject(typeReference, serializer); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * & * & * * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData.toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * @param clazz The {@link Class} representing the Object's type. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} is null. * @see JsonSerializer */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { return toObjectAsync(TypeReference.createInstance(clazz), SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * & * & * * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData.toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * final Person person1 = new Person& * final Person person2 = new Person& * * List&lt;Person&gt; personList = new ArrayList&lt;&gt;& * personList.add& * personList.add& * * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData.toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * @param typeReference The {@link TypeReference} representing the Object's type. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} is null. * @see JsonSerializer */ public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference) { return toObjectAsync(typeReference, SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData.toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * @param clazz The {@link Class} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { return toObjectAsync(TypeReference.createInstance(clazz), serializer); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https: * <li><a href="https: * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * class Person & * & * private String name; * * & * public Person setName& * this.name = name; * return this; * & * * & * public String getName& * return name; * & * & * final Person data = new Person& * * & * & * & * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData * .toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toObjectAsync * <pre> * final Person person1 = new Person& * final Person person2 = new Person& * * List&lt;Person&gt; personList = new ArrayList&lt;&gt;& * personList.add& * personList.add& * * final ObjectSerializer serializer = * new MyJsonSerializer& * BinaryData binaryData = BinaryData.fromObject& * * Disposable subscriber = binaryData * .toObjectAsync& * .subscribe& * * & * TimeUnit.SECONDS.sleep& * subscriber.dispose& * </pre> * <!-- end com.azure.core.util.BinaryData.toObjectAsync * * @param typeReference The {@link TypeReference} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference, ObjectSerializer serializer) { return Mono.fromCallable(() -> toObject(typeReference, serializer)); } /** * Returns an {@link InputStream} representation of this {@link BinaryData}. * * <p><strong>Get an InputStream from the BinaryData</strong></p> * * <!-- src_embed com.azure.core.util.BinaryData.toStream --> * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * BinaryData binaryData = BinaryData.fromStream& * final byte[] bytes = new byte[data.length]; * binaryData.toStream& * System.out.println& * </pre> * <!-- end com.azure.core.util.BinaryData.toStream --> * * @return An {@link InputStream} representing the {@link BinaryData}. */ public InputStream toStream() { return content.toStream(); } /** * Returns a read-only {@link ByteBuffer} representation of this {@link BinaryData}. * <p> * Attempting to mutate the returned {@link ByteBuffer} will throw a {@link ReadOnlyBufferException}. * * <p><strong>Get a read-only ByteBuffer from the BinaryData</strong></p> * * <!-- src_embed com.azure.util.BinaryData.toByteBuffer --> * <pre> * final byte[] data = &quot;Some Data&quot;.getBytes& * BinaryData binaryData = BinaryData.fromBytes& * final byte[] bytes = new byte[data.length]; * binaryData.toByteBuffer& * System.out.println& * </pre> * <!-- end com.azure.util.BinaryData.toByteBuffer --> * * @return A read-only {@link ByteBuffer} representing the {@link BinaryData}. */ public ByteBuffer toByteBuffer() { return content.toByteBuffer(); } /** * Returns the content of this {@link BinaryData} instance as a flux of {@link ByteBuffer ByteBuffers}. The * content is not read from the underlying data source until the {@link Flux} is subscribed to. * * @return the content of this {@link BinaryData} instance as a flux of {@link ByteBuffer ByteBuffers}. */ public Flux<ByteBuffer> toFluxByteBuffer() { return content.toFluxByteBuffer(); } /** * Returns the length of the content, if it is known. The length can be {@code null} if the source did not * specify the length or the length cannot be determined without reading the whole content. * * @return the length of the content, if it is known. */ public Long getLength() { return content.getLength(); } }
Delay the default to `HttpPipelineProvider`. So that code here would now have effect https://github.com/Azure/azure-sdk-for-java/blob/90775e584eb5bae2f8bb929090440ac24ddb6d95/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/implementation/AzureConfigurableImpl.java#L142-L144 (previously `retryPolicy` variable will not be null, and hence `retryOptions` have no effect)
protected AzureConfigurableImpl() { policies = new ArrayList<>(); scopes = new ArrayList<>(); tokens = new ArrayList<>(); httpLogOptions = new HttpLogOptions().setLogLevel(HttpLogDetailLevel.NONE); }
}
protected AzureConfigurableImpl() { policies = new ArrayList<>(); scopes = new ArrayList<>(); tokens = new ArrayList<>(); httpLogOptions = new HttpLogOptions().setLogLevel(HttpLogDetailLevel.NONE); }
class AzureConfigurableImpl<T extends AzureConfigurable<T>> implements AzureConfigurable<T> { private HttpClient httpClient; private HttpLogOptions httpLogOptions; private final List<HttpPipelinePolicy> policies; private final List<String> scopes; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private Configuration configuration; private final List<TokenCredential> tokens; @Override @SuppressWarnings("unchecked") public T withLogOptions(HttpLogOptions httpLogOptions) { Objects.requireNonNull(httpLogOptions); this.httpLogOptions = httpLogOptions; return (T) this; } @Override @SuppressWarnings("unchecked") public T withLogLevel(HttpLogDetailLevel logLevel) { Objects.requireNonNull(logLevel); this.httpLogOptions = httpLogOptions.setLogLevel(logLevel); return (T) this; } @Override @SuppressWarnings("unchecked") public T withPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); policies.add(policy); return (T) this; } @Override @SuppressWarnings("unchecked") public T withAuxiliaryCredential(TokenCredential token) { Objects.requireNonNull(token); this.tokens.add(token); return (T) this; } @Override @SuppressWarnings("unchecked") public T withAuxiliaryCredentials(List<TokenCredential> tokens) { Objects.requireNonNull(tokens); this.tokens.addAll(tokens); return (T) this; } @Override @SuppressWarnings("unchecked") public T withRetryPolicy(RetryPolicy retryPolicy) { Objects.requireNonNull(retryPolicy); this.retryPolicy = retryPolicy; return (T) this; } @Override @SuppressWarnings("unchecked") public T withScope(String scope) { Objects.requireNonNull(scope); this.scopes.add(scope); return (T) this; } @Override @SuppressWarnings("unchecked") public T withScopes(List<String> scopes) { Objects.requireNonNull(scopes); this.scopes.addAll(scopes); return (T) this; } @Override @SuppressWarnings("unchecked") public T withHttpClient(HttpClient httpClient) { Objects.requireNonNull(httpClient); this.httpClient = httpClient; return (T) this; } @Override @SuppressWarnings("unchecked") public T withConfiguration(Configuration configuration) { Objects.requireNonNull(configuration); this.configuration = configuration; return (T) this; } @Override @SuppressWarnings("unchecked") public T withRetryOptions(RetryOptions retryOptions) { Objects.requireNonNull(retryOptions); this.retryOptions = retryOptions; return (T) this; } protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile) { Objects.requireNonNull(credential); if (!tokens.isEmpty()) { policies.add( new AuxiliaryAuthenticationPolicy(profile.getEnvironment(), tokens.toArray(new TokenCredential[0]))); } if (this.retryPolicy == null && this.retryOptions != null) { this.retryPolicy = new RetryPolicy(this.retryOptions); } return HttpPipelineProvider.buildHttpPipeline(credential, profile, scopes(), httpLogOptions, configuration, retryPolicy, policies, httpClient); } private String[] scopes() { return scopes.isEmpty() ? null : scopes.toArray(new String[0]); } }
class AzureConfigurableImpl<T extends AzureConfigurable<T>> implements AzureConfigurable<T> { private HttpClient httpClient; private HttpLogOptions httpLogOptions; private final List<HttpPipelinePolicy> policies; private final List<String> scopes; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private Configuration configuration; private final List<TokenCredential> tokens; @Override @SuppressWarnings("unchecked") public T withLogOptions(HttpLogOptions httpLogOptions) { Objects.requireNonNull(httpLogOptions); this.httpLogOptions = httpLogOptions; return (T) this; } @Override @SuppressWarnings("unchecked") public T withLogLevel(HttpLogDetailLevel logLevel) { Objects.requireNonNull(logLevel); this.httpLogOptions = httpLogOptions.setLogLevel(logLevel); return (T) this; } @Override @SuppressWarnings("unchecked") public T withPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); policies.add(policy); return (T) this; } @Override @SuppressWarnings("unchecked") public T withAuxiliaryCredential(TokenCredential token) { Objects.requireNonNull(token); this.tokens.add(token); return (T) this; } @Override @SuppressWarnings("unchecked") public T withAuxiliaryCredentials(List<TokenCredential> tokens) { Objects.requireNonNull(tokens); this.tokens.addAll(tokens); return (T) this; } @Override @SuppressWarnings("unchecked") public T withRetryPolicy(RetryPolicy retryPolicy) { Objects.requireNonNull(retryPolicy); this.retryPolicy = retryPolicy; return (T) this; } @Override @SuppressWarnings("unchecked") public T withScope(String scope) { Objects.requireNonNull(scope); this.scopes.add(scope); return (T) this; } @Override @SuppressWarnings("unchecked") public T withScopes(List<String> scopes) { Objects.requireNonNull(scopes); this.scopes.addAll(scopes); return (T) this; } @Override @SuppressWarnings("unchecked") public T withHttpClient(HttpClient httpClient) { Objects.requireNonNull(httpClient); this.httpClient = httpClient; return (T) this; } @Override @SuppressWarnings("unchecked") public T withConfiguration(Configuration configuration) { Objects.requireNonNull(configuration); this.configuration = configuration; return (T) this; } @Override @SuppressWarnings("unchecked") public T withRetryOptions(RetryOptions retryOptions) { Objects.requireNonNull(retryOptions); this.retryOptions = retryOptions; return (T) this; } protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile) { Objects.requireNonNull(credential); if (!tokens.isEmpty()) { policies.add( new AuxiliaryAuthenticationPolicy(profile.getEnvironment(), tokens.toArray(new TokenCredential[0]))); } if (this.retryPolicy == null && this.retryOptions != null) { this.retryPolicy = new RetryPolicy(this.retryOptions); } return HttpPipelineProvider.buildHttpPipeline(credential, profile, scopes(), httpLogOptions, configuration, retryPolicy, policies, httpClient); } private String[] scopes() { return scopes.isEmpty() ? null : scopes.toArray(new String[0]); } }
Which class will handle this exception?
protected void doHealthCheck(Builder builder) { if (database == null) { builder.status("The option of `spring.cloud.azure.cosmos.database` is not configured!"); } else { try { CosmosDatabaseResponse response = this.cosmosAsyncClient.getDatabase(database) .read() .block(timeout); if (response != null) { LOGGER.info("The health indicator cost {} RUs, cosmos uri: {}, dbName: {}", response.getRequestCharge(), endpoint, database); } if (response == null) { builder.down(); } else { builder.up().withDetail("database", response.getProperties().getId()); } }catch (Exception e) { if (e instanceof NotFoundException) { builder.status("The option of `spring.cloud.azure.cosmos.database` is not configured correctly!"); } else { throw e; } } } }
throw e;
protected void doHealthCheck(Builder builder) { if (database == null) { builder.status(Status.UNKNOWN).withDetail("Database not configured", "The option of `spring.cloud.azure.cosmos.database` is not configured!"); return; } CosmosDatabaseResponse response = this.cosmosAsyncClient.getDatabase(database) .read() .block(timeout); if (response == null) { throw new RuntimeException("Error occurred checking the database!"); } LOGGER.info("The health indicator cost {} RUs, endpoint: {}, database: {}", response.getRequestCharge(), endpoint, database); builder.up() .withDetail(DATA_BASE_FIELD, database); }
class CosmosHealthIndicator extends AbstractHealthIndicator { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosHealthIndicator.class); private final CosmosAsyncClient cosmosAsyncClient; private final String database; private final String endpoint; private Duration timeout = DEFAULT_HEALTH_CHECK_TIMEOUT; /** * Creates a new instance of {@link CosmosHealthIndicator}. * @param cosmosAsyncClient the cosmosAsyncClient * @param database database name * @param endpoint cosmos endpoint */ public CosmosHealthIndicator(CosmosAsyncClient cosmosAsyncClient, String database, String endpoint) { super("Cosmos health check failed"); Assert.notNull(cosmosAsyncClient, "CosmosClient must not be null"); this.cosmosAsyncClient = cosmosAsyncClient; this.database = database; this.endpoint = endpoint; } @Override /** * Set health check request timeout. * @param timeout the duration value. */ public void setTimeout(Duration timeout) { this.timeout = timeout; } }
class CosmosHealthIndicator extends AbstractHealthIndicator { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosHealthIndicator.class); private final CosmosAsyncClient cosmosAsyncClient; private final String database; private final String endpoint; private Duration timeout = DEFAULT_HEALTH_CHECK_TIMEOUT; /** * Creates a new instance of {@link CosmosHealthIndicator}. * * @param cosmosAsyncClient the cosmosAsyncClient * @param database database name * @param endpoint cosmos endpoint */ public CosmosHealthIndicator(CosmosAsyncClient cosmosAsyncClient, String database, String endpoint) { super("Cosmos health check failed"); Assert.notNull(cosmosAsyncClient, "CosmosClient must not be null"); this.cosmosAsyncClient = cosmosAsyncClient; this.database = database; this.endpoint = endpoint; } @Override /** * Set health check request timeout. * * @param timeout the duration value. */ public void setTimeout(Duration timeout) { this.timeout = timeout; } }