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
gave feedback offline; add comment make this more obvious that it's an invalid dummy token
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0.", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); policies.add(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0.", TestProxySanitizerType.BODY_KEY));
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, INVALID_DUMMY_TOKEN, TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
class MixedRealityStsClientTestBase extends TestProxyTestBase { private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
class MixedRealityStsClientTestBase extends TestProxyTestBase { public static final String INVALID_DUMMY_TOKEN = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b" + "3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZm" + "F1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0."; private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
```suggestion customSanitizer.add(new TestProxySanitizer("$..createdBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..updatedBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); ```
protected void beforeTest() { PurviewWorkflowClientBuilder purviewWorkflowClientbuilder = new PurviewWorkflowClientBuilder(); if (interceptorManager.isPlaybackMode()) { purviewWorkflowClientbuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(new MockTokenCredential()); } else { purviewWorkflowClientbuilder .httpClient(HttpClient.createDefault()) .credential(new DefaultAzureCredentialBuilder().build()); } if (interceptorManager.isRecordMode()) { purviewWorkflowClientbuilder .addPolicy(interceptorManager.getRecordPolicy()); } List<TestProxySanitizer> customSanitizer = new ArrayList<>(); if (!interceptorManager.isLiveMode()) { customSanitizer.add(new TestProxySanitizer("$..requestor", null, "00000000-0000-0000-0000-000000000000", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..createdBy", null, "00000000-0000-0000-0000-000000000000", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..updatedBy", null, "00000000-0000-0000-0000-000000000000", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizer); } purviewWorkflowClient = purviewWorkflowClientbuilder.endpoint(getEndpoint()).buildClient(); }
customSanitizer.add(new TestProxySanitizer("$..updatedBy", null, "00000000-0000-0000-0000-000000000000", TestProxySanitizerType.BODY_KEY));
protected void beforeTest() { PurviewWorkflowClientBuilder purviewWorkflowClientbuilder = new PurviewWorkflowClientBuilder(); if (interceptorManager.isPlaybackMode()) { purviewWorkflowClientbuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(new MockTokenCredential()); } else { purviewWorkflowClientbuilder .httpClient(HttpClient.createDefault()) .credential(new DefaultAzureCredentialBuilder().build()); } if (interceptorManager.isRecordMode()) { purviewWorkflowClientbuilder .addPolicy(interceptorManager.getRecordPolicy()); } List<TestProxySanitizer> customSanitizer = new ArrayList<>(); if (!interceptorManager.isLiveMode()) { customSanitizer.add(new TestProxySanitizer("$..requestor", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..createdBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..updatedBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizer); } purviewWorkflowClient = purviewWorkflowClientbuilder.endpoint(getEndpoint()).buildClient(); }
class PurviewWorkflowClientTestBase extends TestProxyTestBase { protected PurviewWorkflowClient purviewWorkflowClient; protected String getEndpoint() { String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint"); Objects.requireNonNull(endpoint); return endpoint; } @Override }
class PurviewWorkflowClientTestBase extends TestProxyTestBase { protected PurviewWorkflowClient purviewWorkflowClient; protected String getEndpoint() { String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint"); Objects.requireNonNull(endpoint); return endpoint; } @Override }
redact blob url with `sig=`, in response
public RegistryTest() { addSanitizers( new TestProxySanitizer(String.format("$..%s", "uploadUrl"), null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), new TestProxySanitizer(String.format("$..%s", "logLink"), null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY) ); }
new TestProxySanitizer(String.format("$..%s", "logLink"), null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY)
public RegistryTest() { addSanitizers( new TestProxySanitizer(String.format("$..%s", "uploadUrl"), null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), new TestProxySanitizer(String.format("$..%s", "logLink"), null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY) ); }
class RegistryTest extends ResourceManagerTestProxyTestBase { protected ResourceManager resourceManager; protected ContainerRegistryManager registryManager; protected String rgName; private static final String REDACTED_VALUE = "REDACTED"; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { registryManager = buildManager(ContainerRegistryManager.class, httpPipeline, profile); resourceManager = registryManager.resourceManager(); rgName = generateRandomResourceName("rgacr", 10); } }
class RegistryTest extends ResourceManagerTestProxyTestBase { protected ResourceManager resourceManager; protected ContainerRegistryManager registryManager; protected String rgName; private static final String REDACTED_VALUE = "REDACTED"; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { registryManager = buildManager(ContainerRegistryManager.class, httpPipeline, profile); resourceManager = registryManager.resourceManager(); rgName = generateRandomResourceName("rgacr", 10); } }
Should these be named AZURE_CLIENT_ID etc..
protected void beforeTest() { PurviewWorkflowClientBuilder purviewWorkflowClientbuilder = new PurviewWorkflowClientBuilder(); if (interceptorManager.isPlaybackMode()) { purviewWorkflowClientbuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(new MockTokenCredential()); } else { purviewWorkflowClientbuilder .httpClient(HttpClient.createDefault()) .credential(new UsernamePasswordCredentialBuilder() .clientId(Configuration.getGlobalConfiguration().get("CLIENTID", "clientId")) .tenantId(Configuration.getGlobalConfiguration().get("TENANTID", "tenantId")) .username(Configuration.getGlobalConfiguration().get("USERNAME", "username")) .password(Configuration.getGlobalConfiguration().get("PASSWORD", "password")) .authorityHost(Configuration.getGlobalConfiguration().get("HOST", "host")) .build() ); } if (interceptorManager.isRecordMode()) { purviewWorkflowClientbuilder .addPolicy(interceptorManager.getRecordPolicy()); } List<TestProxySanitizer> customSanitizer = new ArrayList<>(); if (!interceptorManager.isLiveMode()) { customSanitizer.add(new TestProxySanitizer("$..requestor", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..createdBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..updatedBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizer); } purviewWorkflowClient = purviewWorkflowClientbuilder.endpoint(getEndpoint()).buildClient(); }
.clientId(Configuration.getGlobalConfiguration().get("CLIENTID", "clientId"))
protected void beforeTest() { PurviewWorkflowClientBuilder purviewWorkflowClientbuilder = new PurviewWorkflowClientBuilder(); if (interceptorManager.isPlaybackMode()) { purviewWorkflowClientbuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(new MockTokenCredential()); } else { purviewWorkflowClientbuilder .httpClient(HttpClient.createDefault()) .credential(new UsernamePasswordCredentialBuilder() .clientId(Configuration.getGlobalConfiguration().get("CLIENTID", "clientId")) .tenantId(Configuration.getGlobalConfiguration().get("TENANTID", "tenantId")) .username(Configuration.getGlobalConfiguration().get("USERNAME", "username")) .password(Configuration.getGlobalConfiguration().get("PASSWORD", "password")) .authorityHost(Configuration.getGlobalConfiguration().get("HOST", "host")) .build() ); } if (interceptorManager.isRecordMode()) { purviewWorkflowClientbuilder .addPolicy(interceptorManager.getRecordPolicy()); } List<TestProxySanitizer> customSanitizer = new ArrayList<>(); if (!interceptorManager.isLiveMode()) { customSanitizer.add(new TestProxySanitizer("$..requestor", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..createdBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..updatedBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizer); } purviewWorkflowClient = purviewWorkflowClientbuilder.endpoint(getEndpoint()).buildClient(); }
class PurviewWorkflowClientTestBase extends TestProxyTestBase { protected PurviewWorkflowClient purviewWorkflowClient; protected String getEndpoint() { String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint"); Objects.requireNonNull(endpoint); return endpoint; } @Override }
class PurviewWorkflowClientTestBase extends TestProxyTestBase { protected PurviewWorkflowClient purviewWorkflowClient; protected String getEndpoint() { String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint"); Objects.requireNonNull(endpoint); return endpoint; } @Override }
It is what the SDK owner uses. I would stay with what it is until they change.
protected void beforeTest() { PurviewWorkflowClientBuilder purviewWorkflowClientbuilder = new PurviewWorkflowClientBuilder(); if (interceptorManager.isPlaybackMode()) { purviewWorkflowClientbuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(new MockTokenCredential()); } else { purviewWorkflowClientbuilder .httpClient(HttpClient.createDefault()) .credential(new UsernamePasswordCredentialBuilder() .clientId(Configuration.getGlobalConfiguration().get("CLIENTID", "clientId")) .tenantId(Configuration.getGlobalConfiguration().get("TENANTID", "tenantId")) .username(Configuration.getGlobalConfiguration().get("USERNAME", "username")) .password(Configuration.getGlobalConfiguration().get("PASSWORD", "password")) .authorityHost(Configuration.getGlobalConfiguration().get("HOST", "host")) .build() ); } if (interceptorManager.isRecordMode()) { purviewWorkflowClientbuilder .addPolicy(interceptorManager.getRecordPolicy()); } List<TestProxySanitizer> customSanitizer = new ArrayList<>(); if (!interceptorManager.isLiveMode()) { customSanitizer.add(new TestProxySanitizer("$..requestor", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..createdBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..updatedBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizer); } purviewWorkflowClient = purviewWorkflowClientbuilder.endpoint(getEndpoint()).buildClient(); }
.clientId(Configuration.getGlobalConfiguration().get("CLIENTID", "clientId"))
protected void beforeTest() { PurviewWorkflowClientBuilder purviewWorkflowClientbuilder = new PurviewWorkflowClientBuilder(); if (interceptorManager.isPlaybackMode()) { purviewWorkflowClientbuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(new MockTokenCredential()); } else { purviewWorkflowClientbuilder .httpClient(HttpClient.createDefault()) .credential(new UsernamePasswordCredentialBuilder() .clientId(Configuration.getGlobalConfiguration().get("CLIENTID", "clientId")) .tenantId(Configuration.getGlobalConfiguration().get("TENANTID", "tenantId")) .username(Configuration.getGlobalConfiguration().get("USERNAME", "username")) .password(Configuration.getGlobalConfiguration().get("PASSWORD", "password")) .authorityHost(Configuration.getGlobalConfiguration().get("HOST", "host")) .build() ); } if (interceptorManager.isRecordMode()) { purviewWorkflowClientbuilder .addPolicy(interceptorManager.getRecordPolicy()); } List<TestProxySanitizer> customSanitizer = new ArrayList<>(); if (!interceptorManager.isLiveMode()) { customSanitizer.add(new TestProxySanitizer("$..requestor", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..createdBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizer.add(new TestProxySanitizer("$..updatedBy", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizer); } purviewWorkflowClient = purviewWorkflowClientbuilder.endpoint(getEndpoint()).buildClient(); }
class PurviewWorkflowClientTestBase extends TestProxyTestBase { protected PurviewWorkflowClient purviewWorkflowClient; protected String getEndpoint() { String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint"); Objects.requireNonNull(endpoint); return endpoint; } @Override }
class PurviewWorkflowClientTestBase extends TestProxyTestBase { protected PurviewWorkflowClient purviewWorkflowClient; protected String getEndpoint() { String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint"); Objects.requireNonNull(endpoint); return endpoint; } @Override }
Is possible we keep using "not_token_looking_string" instead of this fake credential (it looks like it is a possible credential)? I initially thought it will fail the CredScan check but it doesn't. (FWIW, if failed with CredScan check we will need to suppress the credential value by following steps: ``` How to suppress the credential value: Create a client based suppression file, "FakeCredentialConstants". Add the file reference to the global suppression file, "eng/CredScanSuppression.json". Note: Placeholders should be very specific, it could possible over suppress that could result in accidentally suppressing true secret. • Create a java file, "FakeCredentialConstants.java: in the client's /implementation folder. a. Name the value of credential with suffix, "placeholder", e.x., "fakeUsernamePlaceholder". private static final String COMMUNICATION_MSAL_USERNAME = Configuration.getGlobalConfiguration() .get("COMMUNICATION_MSAL_USERNAME", "fakeUsernamePlaceholder"); private static final String COMMUNICATION_MSAL_PASSWORD = Configuration.getGlobalConfiguration() .get("COMMUNICATION_MSAL_PASSWORD", "fakePasswordPlaceholder"); • Add this file reference to "suppressions" array in the eng/CredScanSuppression.json. For example, { "file": [ "sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/implementation/FakeCredentialConstants.java" ], "_justification": "File contains fake key used by implementation code." }, ``` )
public void testGetCompletionsExpiredSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); assertEquals(429, ((HttpResponseException) throwable).getResponse().getStatusCode()); }); }); }
new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678"));
public void testGetCompletionsExpiredSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); assertEquals(429, ((HttpResponseException) throwable).getResponse().getStatusCode()); }); }); }
class NonAzureOpenAIAsyncClientTest extends OpenAIClientTestBase { private OpenAIAsyncClient client; private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .buildAsyncClient(); } private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient, NonAzureOpenAIKeyCredential keyCredential) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .credential(keyCredential) .buildAsyncClient(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, new CompletionsOptions(prompt))) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((deploymentId, prompt) -> { StepVerifier.create(client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> { assertCompletionsStream(chatCompletions); return true; }) .consumeRecordedWith(messageList -> assertTrue(messageList.size() > 1)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsFromPrompt(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsFromSinglePromptRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, prompt)) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .assertNext(response -> { Completions resultCompletions = assertAndGetValueFromResponse(response, Completions.class, 200); assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsBadSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("not_token_looking_string")); client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(ClientAuthenticationException.class, throwable); assertEquals(401, ((ClientAuthenticationException) throwable).getResponse().getStatusCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsUsageField(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(1024); completionsOptions.setN(3); completionsOptions.setLogprobs(1); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> { CompletionsUsage usage = resultCompletions.getUsage(); assertCompletions(completionsOptions.getN() * completionsOptions.getPrompt().size(), resultCompletions); assertNotNull(usage); assertTrue(usage.getTotalTokens() > 0); assertEquals(usage.getCompletionTokens() + usage.getPromptTokens(), usage.getTotalTokens()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(3); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> assertCompletions(1, "length", resultCompletions)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(resultChatCompletions -> { assertNotNull(resultChatCompletions.getUsage()); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((deploymentId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsStream(deploymentId, new ChatCompletionsOptions(chatMessages))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> true) .consumeRecordedWith(messageList -> { assertTrue(messageList.size() > 1); messageList.forEach(OpenAIClientTestBase::assertChatCompletionsStream); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsWithResponse(modelId, BinaryData.fromObject(new ChatCompletionsOptions(chatMessages)), new RequestOptions())) .assertNext(response -> { ChatCompletions resultChatCompletions = assertAndGetValueFromResponse(response, ChatCompletions.class, 200); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddings(modelId, embeddingsOptions)) .assertNext(resultEmbeddings -> assertEmbeddings(resultEmbeddings)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddingsWithResponse(modelId, BinaryData.fromObject(embeddingsOptions), new RequestOptions())) .assertNext(response -> { Embeddings resultEmbeddings = assertAndGetValueFromResponse(response, Embeddings.class, 200); assertEmbeddings(resultEmbeddings); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGenerateImage(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getImageGenerationRunner(options -> StepVerifier.create(client.getImages(options)) .assertNext(OpenAIClientTestBase::assertImageResponse) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.AUTO); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertEquals(1, chatCompletions.getChoices().size()); ChatChoice chatChoice = chatCompletions.getChoices().get(0); MyFunctionCallArguments arguments = assertFunctionCall( chatChoice, "MyFunction", MyFunctionCallArguments.class); assertEquals(arguments.getLocation(), "San Francisco, CA"); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNonePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.NONE); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertChatCompletions(1, "stop", ChatRole.ASSISTANT, chatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNotSuppliedByNamePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(new FunctionCallConfig("NotMyFunction")); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); HttpResponseException httpResponseException = (HttpResponseException) throwable; assertEquals(400, httpResponseException.getResponse().getStatusCode()); assertTrue(httpResponseException.getMessage().contains("Invalid value for 'function_call'")); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsContentFilterRunnerForNonAzure((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(chatCompletions -> { assertNull(chatCompletions.getPromptFilterResults()); assertEquals(1, chatCompletions.getChoices().size()); assertNull(chatCompletions.getChoices().get(0).getContentFilterResults()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsContentFilterRunnerForNonAzure((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(Arrays.asList(prompt)); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(completions -> { assertCompletions(1, completions); assertNull(completions.getPromptFilterResults()); assertNull(completions.getChoices().get(0).getContentFilterResults()); }).verifyComplete(); }); } }
class NonAzureOpenAIAsyncClientTest extends OpenAIClientTestBase { private OpenAIAsyncClient client; private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .buildAsyncClient(); } private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient, NonAzureOpenAIKeyCredential keyCredential) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .credential(keyCredential) .buildAsyncClient(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, new CompletionsOptions(prompt))) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((deploymentId, prompt) -> { StepVerifier.create(client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> { assertCompletionsStream(chatCompletions); return true; }) .consumeRecordedWith(messageList -> assertTrue(messageList.size() > 1)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsFromPrompt(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsFromSinglePromptRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, prompt)) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .assertNext(response -> { Completions resultCompletions = assertAndGetValueFromResponse(response, Completions.class, 200); assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsBadSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("not_token_looking_string")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(ClientAuthenticationException.class, throwable); assertEquals(401, ((ClientAuthenticationException) throwable).getResponse().getStatusCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsUsageField(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(1024); completionsOptions.setN(3); completionsOptions.setLogprobs(1); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> { CompletionsUsage usage = resultCompletions.getUsage(); assertCompletions(completionsOptions.getN() * completionsOptions.getPrompt().size(), resultCompletions); assertNotNull(usage); assertTrue(usage.getTotalTokens() > 0); assertEquals(usage.getCompletionTokens() + usage.getPromptTokens(), usage.getTotalTokens()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(3); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> assertCompletions(1, "length", resultCompletions)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(resultChatCompletions -> { assertNotNull(resultChatCompletions.getUsage()); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((deploymentId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsStream(deploymentId, new ChatCompletionsOptions(chatMessages))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> true) .consumeRecordedWith(messageList -> { assertTrue(messageList.size() > 1); messageList.forEach(OpenAIClientTestBase::assertChatCompletionsStream); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsWithResponse(modelId, BinaryData.fromObject(new ChatCompletionsOptions(chatMessages)), new RequestOptions())) .assertNext(response -> { ChatCompletions resultChatCompletions = assertAndGetValueFromResponse(response, ChatCompletions.class, 200); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddings(modelId, embeddingsOptions)) .assertNext(resultEmbeddings -> assertEmbeddings(resultEmbeddings)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddingsWithResponse(modelId, BinaryData.fromObject(embeddingsOptions), new RequestOptions())) .assertNext(response -> { Embeddings resultEmbeddings = assertAndGetValueFromResponse(response, Embeddings.class, 200); assertEmbeddings(resultEmbeddings); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGenerateImage(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getImageGenerationRunner(options -> StepVerifier.create(client.getImages(options)) .assertNext(OpenAIClientTestBase::assertImageResponse) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.AUTO); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertEquals(1, chatCompletions.getChoices().size()); ChatChoice chatChoice = chatCompletions.getChoices().get(0); MyFunctionCallArguments arguments = assertFunctionCall( chatChoice, "MyFunction", MyFunctionCallArguments.class); assertEquals(arguments.getLocation(), "San Francisco, CA"); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNonePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.NONE); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertChatCompletions(1, "stop", ChatRole.ASSISTANT, chatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNotSuppliedByNamePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(new FunctionCallConfig("NotMyFunction")); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); HttpResponseException httpResponseException = (HttpResponseException) throwable; assertEquals(400, httpResponseException.getResponse().getStatusCode()); assertTrue(httpResponseException.getMessage().contains("Invalid value for 'function_call'")); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsContentFilterRunnerForNonAzure((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(chatCompletions -> { assertNull(chatCompletions.getPromptFilterResults()); assertEquals(1, chatCompletions.getChoices().size()); assertNull(chatCompletions.getChoices().get(0).getContentFilterResults()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsContentFilterRunnerForNonAzure((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(Arrays.asList(prompt)); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(completions -> { assertCompletions(1, completions); assertNull(completions.getPromptFilterResults()); assertNull(completions.getChoices().get(0).getContentFilterResults()); }).verifyComplete(); }); } }
remove this line. The client is re-assigned.
public void testGetCompletionsBadSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("not_token_looking_string")); client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(ClientAuthenticationException.class, throwable); assertEquals(401, ((ClientAuthenticationException) throwable).getResponse().getStatusCode()); }); }); }
client = getNonAzureOpenAIAsyncClient(httpClient);
public void testGetCompletionsBadSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("not_token_looking_string")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(ClientAuthenticationException.class, throwable); assertEquals(401, ((ClientAuthenticationException) throwable).getResponse().getStatusCode()); }); }); }
class NonAzureOpenAIAsyncClientTest extends OpenAIClientTestBase { private OpenAIAsyncClient client; private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .buildAsyncClient(); } private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient, NonAzureOpenAIKeyCredential keyCredential) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .credential(keyCredential) .buildAsyncClient(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, new CompletionsOptions(prompt))) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((deploymentId, prompt) -> { StepVerifier.create(client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> { assertCompletionsStream(chatCompletions); return true; }) .consumeRecordedWith(messageList -> assertTrue(messageList.size() > 1)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsFromPrompt(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsFromSinglePromptRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, prompt)) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .assertNext(response -> { Completions resultCompletions = assertAndGetValueFromResponse(response, Completions.class, 200); assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsExpiredSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); assertEquals(429, ((HttpResponseException) throwable).getResponse().getStatusCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsUsageField(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(1024); completionsOptions.setN(3); completionsOptions.setLogprobs(1); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> { CompletionsUsage usage = resultCompletions.getUsage(); assertCompletions(completionsOptions.getN() * completionsOptions.getPrompt().size(), resultCompletions); assertNotNull(usage); assertTrue(usage.getTotalTokens() > 0); assertEquals(usage.getCompletionTokens() + usage.getPromptTokens(), usage.getTotalTokens()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(3); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> assertCompletions(1, "length", resultCompletions)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(resultChatCompletions -> { assertNotNull(resultChatCompletions.getUsage()); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((deploymentId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsStream(deploymentId, new ChatCompletionsOptions(chatMessages))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> true) .consumeRecordedWith(messageList -> { assertTrue(messageList.size() > 1); messageList.forEach(OpenAIClientTestBase::assertChatCompletionsStream); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsWithResponse(modelId, BinaryData.fromObject(new ChatCompletionsOptions(chatMessages)), new RequestOptions())) .assertNext(response -> { ChatCompletions resultChatCompletions = assertAndGetValueFromResponse(response, ChatCompletions.class, 200); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddings(modelId, embeddingsOptions)) .assertNext(resultEmbeddings -> assertEmbeddings(resultEmbeddings)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddingsWithResponse(modelId, BinaryData.fromObject(embeddingsOptions), new RequestOptions())) .assertNext(response -> { Embeddings resultEmbeddings = assertAndGetValueFromResponse(response, Embeddings.class, 200); assertEmbeddings(resultEmbeddings); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGenerateImage(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getImageGenerationRunner(options -> StepVerifier.create(client.getImages(options)) .assertNext(OpenAIClientTestBase::assertImageResponse) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.AUTO); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertEquals(1, chatCompletions.getChoices().size()); ChatChoice chatChoice = chatCompletions.getChoices().get(0); MyFunctionCallArguments arguments = assertFunctionCall( chatChoice, "MyFunction", MyFunctionCallArguments.class); assertEquals(arguments.getLocation(), "San Francisco, CA"); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNonePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.NONE); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertChatCompletions(1, "stop", ChatRole.ASSISTANT, chatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNotSuppliedByNamePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(new FunctionCallConfig("NotMyFunction")); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); HttpResponseException httpResponseException = (HttpResponseException) throwable; assertEquals(400, httpResponseException.getResponse().getStatusCode()); assertTrue(httpResponseException.getMessage().contains("Invalid value for 'function_call'")); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsContentFilterRunnerForNonAzure((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(chatCompletions -> { assertNull(chatCompletions.getPromptFilterResults()); assertEquals(1, chatCompletions.getChoices().size()); assertNull(chatCompletions.getChoices().get(0).getContentFilterResults()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsContentFilterRunnerForNonAzure((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(Arrays.asList(prompt)); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(completions -> { assertCompletions(1, completions); assertNull(completions.getPromptFilterResults()); assertNull(completions.getChoices().get(0).getContentFilterResults()); }).verifyComplete(); }); } }
class NonAzureOpenAIAsyncClientTest extends OpenAIClientTestBase { private OpenAIAsyncClient client; private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .buildAsyncClient(); } private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient, NonAzureOpenAIKeyCredential keyCredential) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .credential(keyCredential) .buildAsyncClient(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, new CompletionsOptions(prompt))) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((deploymentId, prompt) -> { StepVerifier.create(client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> { assertCompletionsStream(chatCompletions); return true; }) .consumeRecordedWith(messageList -> assertTrue(messageList.size() > 1)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsFromPrompt(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsFromSinglePromptRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, prompt)) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .assertNext(response -> { Completions resultCompletions = assertAndGetValueFromResponse(response, Completions.class, 200); assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsExpiredSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); assertEquals(429, ((HttpResponseException) throwable).getResponse().getStatusCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsUsageField(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(1024); completionsOptions.setN(3); completionsOptions.setLogprobs(1); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> { CompletionsUsage usage = resultCompletions.getUsage(); assertCompletions(completionsOptions.getN() * completionsOptions.getPrompt().size(), resultCompletions); assertNotNull(usage); assertTrue(usage.getTotalTokens() > 0); assertEquals(usage.getCompletionTokens() + usage.getPromptTokens(), usage.getTotalTokens()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(3); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> assertCompletions(1, "length", resultCompletions)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(resultChatCompletions -> { assertNotNull(resultChatCompletions.getUsage()); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((deploymentId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsStream(deploymentId, new ChatCompletionsOptions(chatMessages))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> true) .consumeRecordedWith(messageList -> { assertTrue(messageList.size() > 1); messageList.forEach(OpenAIClientTestBase::assertChatCompletionsStream); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsWithResponse(modelId, BinaryData.fromObject(new ChatCompletionsOptions(chatMessages)), new RequestOptions())) .assertNext(response -> { ChatCompletions resultChatCompletions = assertAndGetValueFromResponse(response, ChatCompletions.class, 200); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddings(modelId, embeddingsOptions)) .assertNext(resultEmbeddings -> assertEmbeddings(resultEmbeddings)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddingsWithResponse(modelId, BinaryData.fromObject(embeddingsOptions), new RequestOptions())) .assertNext(response -> { Embeddings resultEmbeddings = assertAndGetValueFromResponse(response, Embeddings.class, 200); assertEmbeddings(resultEmbeddings); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGenerateImage(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getImageGenerationRunner(options -> StepVerifier.create(client.getImages(options)) .assertNext(OpenAIClientTestBase::assertImageResponse) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.AUTO); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertEquals(1, chatCompletions.getChoices().size()); ChatChoice chatChoice = chatCompletions.getChoices().get(0); MyFunctionCallArguments arguments = assertFunctionCall( chatChoice, "MyFunction", MyFunctionCallArguments.class); assertEquals(arguments.getLocation(), "San Francisco, CA"); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNonePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.NONE); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertChatCompletions(1, "stop", ChatRole.ASSISTANT, chatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNotSuppliedByNamePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(new FunctionCallConfig("NotMyFunction")); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); HttpResponseException httpResponseException = (HttpResponseException) throwable; assertEquals(400, httpResponseException.getResponse().getStatusCode()); assertTrue(httpResponseException.getMessage().contains("Invalid value for 'function_call'")); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsContentFilterRunnerForNonAzure((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(chatCompletions -> { assertNull(chatCompletions.getPromptFilterResults()); assertEquals(1, chatCompletions.getChoices().size()); assertNull(chatCompletions.getChoices().get(0).getContentFilterResults()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsContentFilterRunnerForNonAzure((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(Arrays.asList(prompt)); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(completions -> { assertCompletions(1, completions); assertNull(completions.getPromptFilterResults()); assertNull(completions.getChoices().get(0).getContentFilterResults()); }).verifyComplete(); }); } }
Well, the thing is that these 2 values do in fact produce a different HTTP response status code. So I am not sure what would be a better fake but "conforming to" format value. OpenAI keys seem to comply with the following pattern: `sk-<48_hex_chars>`. Alternatively, I think we could also just get rid of these tests. Originally, for the recording, I used a personal expired key. WDYT?
public void testGetCompletionsExpiredSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); assertEquals(429, ((HttpResponseException) throwable).getResponse().getStatusCode()); }); }); }
new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678"));
public void testGetCompletionsExpiredSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); assertEquals(429, ((HttpResponseException) throwable).getResponse().getStatusCode()); }); }); }
class NonAzureOpenAIAsyncClientTest extends OpenAIClientTestBase { private OpenAIAsyncClient client; private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .buildAsyncClient(); } private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient, NonAzureOpenAIKeyCredential keyCredential) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .credential(keyCredential) .buildAsyncClient(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, new CompletionsOptions(prompt))) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((deploymentId, prompt) -> { StepVerifier.create(client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> { assertCompletionsStream(chatCompletions); return true; }) .consumeRecordedWith(messageList -> assertTrue(messageList.size() > 1)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsFromPrompt(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsFromSinglePromptRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, prompt)) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .assertNext(response -> { Completions resultCompletions = assertAndGetValueFromResponse(response, Completions.class, 200); assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsBadSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("not_token_looking_string")); client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(ClientAuthenticationException.class, throwable); assertEquals(401, ((ClientAuthenticationException) throwable).getResponse().getStatusCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsUsageField(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(1024); completionsOptions.setN(3); completionsOptions.setLogprobs(1); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> { CompletionsUsage usage = resultCompletions.getUsage(); assertCompletions(completionsOptions.getN() * completionsOptions.getPrompt().size(), resultCompletions); assertNotNull(usage); assertTrue(usage.getTotalTokens() > 0); assertEquals(usage.getCompletionTokens() + usage.getPromptTokens(), usage.getTotalTokens()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(3); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> assertCompletions(1, "length", resultCompletions)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(resultChatCompletions -> { assertNotNull(resultChatCompletions.getUsage()); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((deploymentId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsStream(deploymentId, new ChatCompletionsOptions(chatMessages))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> true) .consumeRecordedWith(messageList -> { assertTrue(messageList.size() > 1); messageList.forEach(OpenAIClientTestBase::assertChatCompletionsStream); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsWithResponse(modelId, BinaryData.fromObject(new ChatCompletionsOptions(chatMessages)), new RequestOptions())) .assertNext(response -> { ChatCompletions resultChatCompletions = assertAndGetValueFromResponse(response, ChatCompletions.class, 200); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddings(modelId, embeddingsOptions)) .assertNext(resultEmbeddings -> assertEmbeddings(resultEmbeddings)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddingsWithResponse(modelId, BinaryData.fromObject(embeddingsOptions), new RequestOptions())) .assertNext(response -> { Embeddings resultEmbeddings = assertAndGetValueFromResponse(response, Embeddings.class, 200); assertEmbeddings(resultEmbeddings); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGenerateImage(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getImageGenerationRunner(options -> StepVerifier.create(client.getImages(options)) .assertNext(OpenAIClientTestBase::assertImageResponse) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.AUTO); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertEquals(1, chatCompletions.getChoices().size()); ChatChoice chatChoice = chatCompletions.getChoices().get(0); MyFunctionCallArguments arguments = assertFunctionCall( chatChoice, "MyFunction", MyFunctionCallArguments.class); assertEquals(arguments.getLocation(), "San Francisco, CA"); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNonePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.NONE); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertChatCompletions(1, "stop", ChatRole.ASSISTANT, chatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNotSuppliedByNamePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(new FunctionCallConfig("NotMyFunction")); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); HttpResponseException httpResponseException = (HttpResponseException) throwable; assertEquals(400, httpResponseException.getResponse().getStatusCode()); assertTrue(httpResponseException.getMessage().contains("Invalid value for 'function_call'")); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsContentFilterRunnerForNonAzure((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(chatCompletions -> { assertNull(chatCompletions.getPromptFilterResults()); assertEquals(1, chatCompletions.getChoices().size()); assertNull(chatCompletions.getChoices().get(0).getContentFilterResults()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsContentFilterRunnerForNonAzure((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(Arrays.asList(prompt)); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(completions -> { assertCompletions(1, completions); assertNull(completions.getPromptFilterResults()); assertNull(completions.getChoices().get(0).getContentFilterResults()); }).verifyComplete(); }); } }
class NonAzureOpenAIAsyncClientTest extends OpenAIClientTestBase { private OpenAIAsyncClient client; private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .buildAsyncClient(); } private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient, NonAzureOpenAIKeyCredential keyCredential) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .credential(keyCredential) .buildAsyncClient(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, new CompletionsOptions(prompt))) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((deploymentId, prompt) -> { StepVerifier.create(client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> { assertCompletionsStream(chatCompletions); return true; }) .consumeRecordedWith(messageList -> assertTrue(messageList.size() > 1)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsFromPrompt(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsFromSinglePromptRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, prompt)) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .assertNext(response -> { Completions resultCompletions = assertAndGetValueFromResponse(response, Completions.class, 200); assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsBadSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("not_token_looking_string")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(ClientAuthenticationException.class, throwable); assertEquals(401, ((ClientAuthenticationException) throwable).getResponse().getStatusCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsUsageField(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(1024); completionsOptions.setN(3); completionsOptions.setLogprobs(1); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> { CompletionsUsage usage = resultCompletions.getUsage(); assertCompletions(completionsOptions.getN() * completionsOptions.getPrompt().size(), resultCompletions); assertNotNull(usage); assertTrue(usage.getTotalTokens() > 0); assertEquals(usage.getCompletionTokens() + usage.getPromptTokens(), usage.getTotalTokens()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(3); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> assertCompletions(1, "length", resultCompletions)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(resultChatCompletions -> { assertNotNull(resultChatCompletions.getUsage()); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((deploymentId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsStream(deploymentId, new ChatCompletionsOptions(chatMessages))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> true) .consumeRecordedWith(messageList -> { assertTrue(messageList.size() > 1); messageList.forEach(OpenAIClientTestBase::assertChatCompletionsStream); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsWithResponse(modelId, BinaryData.fromObject(new ChatCompletionsOptions(chatMessages)), new RequestOptions())) .assertNext(response -> { ChatCompletions resultChatCompletions = assertAndGetValueFromResponse(response, ChatCompletions.class, 200); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddings(modelId, embeddingsOptions)) .assertNext(resultEmbeddings -> assertEmbeddings(resultEmbeddings)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddingsWithResponse(modelId, BinaryData.fromObject(embeddingsOptions), new RequestOptions())) .assertNext(response -> { Embeddings resultEmbeddings = assertAndGetValueFromResponse(response, Embeddings.class, 200); assertEmbeddings(resultEmbeddings); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGenerateImage(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getImageGenerationRunner(options -> StepVerifier.create(client.getImages(options)) .assertNext(OpenAIClientTestBase::assertImageResponse) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.AUTO); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertEquals(1, chatCompletions.getChoices().size()); ChatChoice chatChoice = chatCompletions.getChoices().get(0); MyFunctionCallArguments arguments = assertFunctionCall( chatChoice, "MyFunction", MyFunctionCallArguments.class); assertEquals(arguments.getLocation(), "San Francisco, CA"); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNonePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.NONE); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertChatCompletions(1, "stop", ChatRole.ASSISTANT, chatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNotSuppliedByNamePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(new FunctionCallConfig("NotMyFunction")); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); HttpResponseException httpResponseException = (HttpResponseException) throwable; assertEquals(400, httpResponseException.getResponse().getStatusCode()); assertTrue(httpResponseException.getMessage().contains("Invalid value for 'function_call'")); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsContentFilterRunnerForNonAzure((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(chatCompletions -> { assertNull(chatCompletions.getPromptFilterResults()); assertEquals(1, chatCompletions.getChoices().size()); assertNull(chatCompletions.getChoices().get(0).getContentFilterResults()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsContentFilterRunnerForNonAzure((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(Arrays.asList(prompt)); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(completions -> { assertCompletions(1, completions); assertNull(completions.getPromptFilterResults()); assertNull(completions.getChoices().get(0).getContentFilterResults()); }).verifyComplete(); }); } }
nit, same here, it usually better to call `analyzeImage` Please check Async client as well.
public AnalyzeImageResult analyzeImage(BinaryData content) { RequestOptions requestOptions = new RequestOptions(); AnalyzeImageOptions body = new AnalyzeImageOptions(new ContentSafetyImageData().setContent(content)); return analyzeImageWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeImageResult.class); }
.toObject(AnalyzeImageResult.class);
public AnalyzeImageResult analyzeImage(BinaryData content) { AnalyzeImageOptions body = new AnalyzeImageOptions(new ContentSafetyImageData().setContent(content)); return analyzeImage(body); }
class ContentSafetyClient { @Generated private final ContentSafetyClientImpl serviceClient; /** * Initializes an instance of ContentSafetyClient class. * * @param serviceClient the service client implementation. */ @Generated ContentSafetyClient(ContentSafetyClientImpl serviceClient) { this.serviceClient = serviceClient; } /** * Analyze Text * * <p>A synchronous API for the analysis of potentially harmful text content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * text: String (Required) * categories (Optional): [ * String(Hate/SelfHarm/Sexual/Violence) (Optional) * ] * blocklistNames (Optional): [ * String (Optional) * ] * haltOnBlocklistHit: Boolean (Optional) * outputType: String(FourSeverityLevels/EightSeverityLevels) (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * blocklistsMatch (Optional): [ * (Optional){ * blocklistName: String (Required) * blocklistItemId: String (Required) * blocklistItemText: String (Required) * } * ] * categoriesAnalysis (Required): [ * (Required){ * category: String(Hate/SelfHarm/Sexual/Violence) (Required) * severity: Integer (Optional) * } * ] * } * }</pre> * * @param body The text analysis request. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the text analysis response along with {@link Response}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Response<BinaryData> analyzeTextWithResponse(BinaryData body, RequestOptions requestOptions) { return this.serviceClient.analyzeTextWithResponse(body, requestOptions); } /** * Analyze Image * * <p>A synchronous API for the analysis of potentially harmful image content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * image (Required): { * content: byte[] (Optional) * blobUrl: String (Optional) * } * categories (Optional): [ * String(Hate/SelfHarm/Sexual/Violence) (Optional) * ] * outputType: String(FourSeverityLevels) (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * categoriesAnalysis (Required): [ * (Required){ * category: String(Hate/SelfHarm/Sexual/Violence) (Required) * severity: Integer (Optional) * } * ] * } * }</pre> * * @param body The image analysis request. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the image analysis response along with {@link Response}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Response<BinaryData> analyzeImageWithResponse(BinaryData body, RequestOptions requestOptions) { return this.serviceClient.analyzeImageWithResponse(body, requestOptions); } /** * Analyze Text * * <p>A synchronous API for the analysis of potentially harmful text content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param body The text analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the text analysis response. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeTextResult analyzeText(AnalyzeTextOptions body) { RequestOptions requestOptions = new RequestOptions(); return analyzeTextWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeTextResult.class); } /** * Analyze Text * * <p>A synchronous API for the analysis of potentially harmful text content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param text The text. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the text analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeTextResult analyzeText(String text) { RequestOptions requestOptions = new RequestOptions(); AnalyzeTextOptions body = new AnalyzeTextOptions(text); return analyzeTextWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeTextResult.class); } /** * Analyze Image * * <p>A synchronous API for the analysis of potentially harmful image content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param body The image analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeImageResult analyzeImage(AnalyzeImageOptions body) { RequestOptions requestOptions = new RequestOptions(); return analyzeImageWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeImageResult.class); } /** * Analyze Image * * <p>A synchronous API for the analysis of potentially harmful image content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param blobUri A string of blob url. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeImageResult analyzeImage(String blobUri) { RequestOptions requestOptions = new RequestOptions(); AnalyzeImageOptions body = new AnalyzeImageOptions(new ContentSafetyImageData().setBlobUri(blobUri)); return analyzeImageWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeImageResult.class); } /** * Analyze Image * * <p>A synchronous API for the analysis of potentially harmful image content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param content A list of bytes of content. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) }
class ContentSafetyClient { @Generated private final ContentSafetyClientImpl serviceClient; /** * Initializes an instance of ContentSafetyClient class. * * @param serviceClient the service client implementation. */ @Generated ContentSafetyClient(ContentSafetyClientImpl serviceClient) { this.serviceClient = serviceClient; } /** * Analyze Text * * A synchronous API for the analysis of potentially harmful text content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * <p> * <strong>Request Body Schema</strong> * </p> * <pre>{@code * { * text: String (Required) * categories (Optional): [ * String(Hate/SelfHarm/Sexual/Violence) (Optional) * ] * blocklistNames (Optional): [ * String (Optional) * ] * haltOnBlocklistHit: Boolean (Optional) * outputType: String(FourSeverityLevels/EightSeverityLevels) (Optional) * } * }</pre> * <p> * <strong>Response Body Schema</strong> * </p> * <pre>{@code * { * blocklistsMatch (Optional): [ * (Optional){ * blocklistName: String (Required) * blocklistItemId: String (Required) * blocklistItemText: String (Required) * } * ] * categoriesAnalysis (Required): [ * (Required){ * category: String(Hate/SelfHarm/Sexual/Violence) (Required) * severity: Integer (Optional) * } * ] * } * }</pre> * * @param options The text analysis request. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the text analysis response along with {@link Response}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Response<BinaryData> analyzeTextWithResponse(BinaryData options, RequestOptions requestOptions) { return this.serviceClient.analyzeTextWithResponse(options, requestOptions); } /** * Analyze Image * * A synchronous API for the analysis of potentially harmful image content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * <p> * <strong>Request Body Schema</strong> * </p> * <pre>{@code * { * image (Required): { * content: byte[] (Optional) * blobUrl: String (Optional) * } * categories (Optional): [ * String(Hate/SelfHarm/Sexual/Violence) (Optional) * ] * outputType: String(FourSeverityLevels) (Optional) * } * }</pre> * <p> * <strong>Response Body Schema</strong> * </p> * <pre>{@code * { * categoriesAnalysis (Required): [ * (Required){ * category: String(Hate/SelfHarm/Sexual/Violence) (Required) * severity: Integer (Optional) * } * ] * } * }</pre> * * @param options The image analysis request. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the image analysis response along with {@link Response}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Response<BinaryData> analyzeImageWithResponse(BinaryData options, RequestOptions requestOptions) { return this.serviceClient.analyzeImageWithResponse(options, requestOptions); } /** * Analyze Text * * A synchronous API for the analysis of potentially harmful text content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param options The text analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the text analysis response. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeTextResult analyzeText(AnalyzeTextOptions options) { RequestOptions requestOptions = new RequestOptions(); return analyzeTextWithResponse(BinaryData.fromObject(options), requestOptions).getValue() .toObject(AnalyzeTextResult.class); } /** * Analyze Text * * A synchronous API for the analysis of potentially harmful text content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param text The text analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the text analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeTextResult analyzeText(String text) { AnalyzeTextOptions options = new AnalyzeTextOptions(text); return analyzeText(options); } /** * Analyze Image * * A synchronous API for the analysis of potentially harmful image content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param options The image analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeImageResult analyzeImage(AnalyzeImageOptions options) { RequestOptions requestOptions = new RequestOptions(); return analyzeImageWithResponse(BinaryData.fromObject(options), requestOptions).getValue() .toObject(AnalyzeImageResult.class); } /** * Analyze Image * * A synchronous API for the analysis of potentially harmful image content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param blobUrl The image analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeImageResult analyzeImage(String blobUrl) { AnalyzeImageOptions body = new AnalyzeImageOptions(new ContentSafetyImageData().setBlobUrl(blobUrl)); return analyzeImage(body); } /** * Analyze Image * * A synchronous API for the analysis of potentially harmful image content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param content The image analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) }
In this case, we can keep the changes here and will suppress the CredScan if failed.
public void testGetCompletionsExpiredSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); assertEquals(429, ((HttpResponseException) throwable).getResponse().getStatusCode()); }); }); }
new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678"));
public void testGetCompletionsExpiredSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("sk-123456789012345678901234567890123456789012345678")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); assertEquals(429, ((HttpResponseException) throwable).getResponse().getStatusCode()); }); }); }
class NonAzureOpenAIAsyncClientTest extends OpenAIClientTestBase { private OpenAIAsyncClient client; private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .buildAsyncClient(); } private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient, NonAzureOpenAIKeyCredential keyCredential) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .credential(keyCredential) .buildAsyncClient(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, new CompletionsOptions(prompt))) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((deploymentId, prompt) -> { StepVerifier.create(client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> { assertCompletionsStream(chatCompletions); return true; }) .consumeRecordedWith(messageList -> assertTrue(messageList.size() > 1)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsFromPrompt(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsFromSinglePromptRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, prompt)) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .assertNext(response -> { Completions resultCompletions = assertAndGetValueFromResponse(response, Completions.class, 200); assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsBadSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("not_token_looking_string")); client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(ClientAuthenticationException.class, throwable); assertEquals(401, ((ClientAuthenticationException) throwable).getResponse().getStatusCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsUsageField(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(1024); completionsOptions.setN(3); completionsOptions.setLogprobs(1); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> { CompletionsUsage usage = resultCompletions.getUsage(); assertCompletions(completionsOptions.getN() * completionsOptions.getPrompt().size(), resultCompletions); assertNotNull(usage); assertTrue(usage.getTotalTokens() > 0); assertEquals(usage.getCompletionTokens() + usage.getPromptTokens(), usage.getTotalTokens()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(3); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> assertCompletions(1, "length", resultCompletions)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(resultChatCompletions -> { assertNotNull(resultChatCompletions.getUsage()); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((deploymentId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsStream(deploymentId, new ChatCompletionsOptions(chatMessages))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> true) .consumeRecordedWith(messageList -> { assertTrue(messageList.size() > 1); messageList.forEach(OpenAIClientTestBase::assertChatCompletionsStream); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsWithResponse(modelId, BinaryData.fromObject(new ChatCompletionsOptions(chatMessages)), new RequestOptions())) .assertNext(response -> { ChatCompletions resultChatCompletions = assertAndGetValueFromResponse(response, ChatCompletions.class, 200); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddings(modelId, embeddingsOptions)) .assertNext(resultEmbeddings -> assertEmbeddings(resultEmbeddings)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddingsWithResponse(modelId, BinaryData.fromObject(embeddingsOptions), new RequestOptions())) .assertNext(response -> { Embeddings resultEmbeddings = assertAndGetValueFromResponse(response, Embeddings.class, 200); assertEmbeddings(resultEmbeddings); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGenerateImage(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getImageGenerationRunner(options -> StepVerifier.create(client.getImages(options)) .assertNext(OpenAIClientTestBase::assertImageResponse) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.AUTO); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertEquals(1, chatCompletions.getChoices().size()); ChatChoice chatChoice = chatCompletions.getChoices().get(0); MyFunctionCallArguments arguments = assertFunctionCall( chatChoice, "MyFunction", MyFunctionCallArguments.class); assertEquals(arguments.getLocation(), "San Francisco, CA"); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNonePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.NONE); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertChatCompletions(1, "stop", ChatRole.ASSISTANT, chatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNotSuppliedByNamePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(new FunctionCallConfig("NotMyFunction")); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); HttpResponseException httpResponseException = (HttpResponseException) throwable; assertEquals(400, httpResponseException.getResponse().getStatusCode()); assertTrue(httpResponseException.getMessage().contains("Invalid value for 'function_call'")); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsContentFilterRunnerForNonAzure((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(chatCompletions -> { assertNull(chatCompletions.getPromptFilterResults()); assertEquals(1, chatCompletions.getChoices().size()); assertNull(chatCompletions.getChoices().get(0).getContentFilterResults()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsContentFilterRunnerForNonAzure((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(Arrays.asList(prompt)); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(completions -> { assertCompletions(1, completions); assertNull(completions.getPromptFilterResults()); assertNull(completions.getChoices().get(0).getContentFilterResults()); }).verifyComplete(); }); } }
class NonAzureOpenAIAsyncClientTest extends OpenAIClientTestBase { private OpenAIAsyncClient client; private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .buildAsyncClient(); } private OpenAIAsyncClient getNonAzureOpenAIAsyncClient(HttpClient httpClient, NonAzureOpenAIKeyCredential keyCredential) { return getNonAzureOpenAIClientBuilder( interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .credential(keyCredential) .buildAsyncClient(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, new CompletionsOptions(prompt))) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((deploymentId, prompt) -> { StepVerifier.create(client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> { assertCompletionsStream(chatCompletions); return true; }) .consumeRecordedWith(messageList -> assertTrue(messageList.size() > 1)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsFromPrompt(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsFromSinglePromptRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletions(modelId, prompt)) .assertNext(resultCompletions -> { assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .assertNext(response -> { Completions resultCompletions = assertAndGetValueFromResponse(response, Completions.class, 200); assertCompletions(1, resultCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsBadSecretKey(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient( httpClient, new NonAzureOpenAIKeyCredential("not_token_looking_string")); getCompletionsRunner((modelId, prompt) -> { StepVerifier.create(client.getCompletionsWithResponse(modelId, BinaryData.fromObject(new CompletionsOptions(prompt)), new RequestOptions())) .verifyErrorSatisfies(throwable -> { assertInstanceOf(ClientAuthenticationException.class, throwable); assertEquals(401, ((ClientAuthenticationException) throwable).getResponse().getStatusCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsUsageField(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(1024); completionsOptions.setN(3); completionsOptions.setLogprobs(1); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> { CompletionsUsage usage = resultCompletions.getUsage(); assertCompletions(completionsOptions.getN() * completionsOptions.getPrompt().size(), resultCompletions); assertNotNull(usage); assertTrue(usage.getTotalTokens() > 0); assertEquals(usage.getCompletionTokens() + usage.getPromptTokens(), usage.getTotalTokens()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsRunner((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(prompt); completionsOptions.setMaxTokens(3); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(resultCompletions -> assertCompletions(1, "length", resultCompletions)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(resultChatCompletions -> { assertNotNull(resultChatCompletions.getUsage()); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsStream(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((deploymentId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsStream(deploymentId, new ChatCompletionsOptions(chatMessages))) .recordWith(ArrayList::new) .thenConsumeWhile(chatCompletions -> true) .consumeRecordedWith(messageList -> { assertTrue(messageList.size() > 1); messageList.forEach(OpenAIClientTestBase::assertChatCompletionsStream); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsForNonAzureRunner((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletionsWithResponse(modelId, BinaryData.fromObject(new ChatCompletionsOptions(chatMessages)), new RequestOptions())) .assertNext(response -> { ChatCompletions resultChatCompletions = assertAndGetValueFromResponse(response, ChatCompletions.class, 200); assertChatCompletions(1, resultChatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddings(modelId, embeddingsOptions)) .assertNext(resultEmbeddings -> assertEmbeddings(resultEmbeddings)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getEmbeddingNonAzureRunner((modelId, embeddingsOptions) -> { StepVerifier.create(client.getEmbeddingsWithResponse(modelId, BinaryData.fromObject(embeddingsOptions), new RequestOptions())) .assertNext(response -> { Embeddings resultEmbeddings = assertAndGetValueFromResponse(response, Embeddings.class, 200); assertEmbeddings(resultEmbeddings); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testGenerateImage(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getImageGenerationRunner(options -> StepVerifier.create(client.getImages(options)) .assertNext(OpenAIClientTestBase::assertImageResponse) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.AUTO); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertEquals(1, chatCompletions.getChoices().size()); ChatChoice chatChoice = chatCompletions.getChoices().get(0); MyFunctionCallArguments arguments = assertFunctionCall( chatChoice, "MyFunction", MyFunctionCallArguments.class); assertEquals(arguments.getLocation(), "San Francisco, CA"); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNonePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(FunctionCallConfig.NONE); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .assertNext(chatCompletions -> { assertChatCompletions(1, "stop", ChatRole.ASSISTANT, chatCompletions); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatFunctionNotSuppliedByNamePreset(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatFunctionForNonAzureRunner((modelId, chatCompletionsOptions) -> { chatCompletionsOptions.setFunctionCall(new FunctionCallConfig("NotMyFunction")); StepVerifier.create(client.getChatCompletions(modelId, chatCompletionsOptions)) .verifyErrorSatisfies(throwable -> { assertInstanceOf(HttpResponseException.class, throwable); HttpResponseException httpResponseException = (HttpResponseException) throwable; assertEquals(400, httpResponseException.getResponse().getStatusCode()); assertTrue(httpResponseException.getMessage().contains("Invalid value for 'function_call'")); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testChatCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getChatCompletionsContentFilterRunnerForNonAzure((modelId, chatMessages) -> { StepVerifier.create(client.getChatCompletions(modelId, new ChatCompletionsOptions(chatMessages))) .assertNext(chatCompletions -> { assertNull(chatCompletions.getPromptFilterResults()); assertEquals(1, chatCompletions.getChoices().size()); assertNull(chatCompletions.getChoices().get(0).getContentFilterResults()); }) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils public void testCompletionContentFiltering(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { client = getNonAzureOpenAIAsyncClient(httpClient); getCompletionsContentFilterRunnerForNonAzure((modelId, prompt) -> { CompletionsOptions completionsOptions = new CompletionsOptions(Arrays.asList(prompt)); StepVerifier.create(client.getCompletions(modelId, completionsOptions)) .assertNext(completions -> { assertCompletions(1, completions); assertNull(completions.getPromptFilterResults()); assertNull(completions.getChoices().get(0).getContentFilterResults()); }).verifyComplete(); }); } }
nit; period goes on next line as well.
ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl). logPii(options.isSupportLoggingEnabled()). instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }
logPii(options.isSupportLoggingEnabled()).
ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl) .logPii(options.isSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder. logPii(options.isSupportLoggingEnabled()). authority(authorityUrl). instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder. logPii(options.isSupportLoggingEnabled()). authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder. validateAuthority(false). logPii(options.isSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azdCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError( new IllegalStateException( "A Safe Working directory could not be" + " found to execute Azure Developer CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(options.getClientOptions(), httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); if (options.getClientOptions() != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); options.getClientOptions().getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder .logPii(options.isSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder .validateAuthority(false) .logPii(options.isSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azdCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError( new IllegalStateException( "A Safe Working directory could not be" + " found to execute Azure Developer CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(options.getClientOptions(), httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); if (options.getClientOptions() != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); options.getClientOptions().getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } }
this part "update a private endpoint connection" seems no longer allowed (or not allowed by storage). may do more investigation later.
public void testPrivateEndpoint() { String peName2 = generateRandomResourceName("pe", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(storageAccount) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .withManualApproval("request message") .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request message", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); List<PrivateEndpointConnection> storageAccountConnections = storageAccount.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, storageAccountConnections.size()); PrivateEndpointConnection storageAccountConnection = storageAccountConnections.iterator().next(); Assertions.assertNotNull(storageAccountConnection.id()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint().id()); Assertions.assertNotNull(storageAccountConnection.privateLinkServiceConnectionState()); Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, storageAccountConnection.privateLinkServiceConnectionState().status()); storageAccount.approvePrivateEndpointConnection(storageAccountConnection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); azureResourceManager.privateEndpoints().deleteById(privateEndpoint.id()); privateEndpoint = azureResourceManager.privateEndpoints().define(peName2) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); List<PrivateEndpoint> privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList()); Assertions.assertEquals(1, privateEndpoints.size()); Assertions.assertEquals(peName2, privateEndpoints.get(0).name()); }
public void testPrivateEndpoint() { String peName2 = generateRandomResourceName("pe", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(storageAccount) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .withManualApproval("request message") .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request message", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); List<PrivateEndpointConnection> storageAccountConnections = storageAccount.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, storageAccountConnections.size()); PrivateEndpointConnection storageAccountConnection = storageAccountConnections.iterator().next(); Assertions.assertNotNull(storageAccountConnection.id()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint().id()); Assertions.assertNotNull(storageAccountConnection.privateLinkServiceConnectionState()); Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, storageAccountConnection.privateLinkServiceConnectionState().status()); storageAccount.approvePrivateEndpointConnection(storageAccountConnection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); azureResourceManager.privateEndpoints().deleteById(privateEndpoint.id()); privateEndpoint = azureResourceManager.privateEndpoints().define(peName2) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); List<PrivateEndpoint> privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList()); Assertions.assertEquals(1, privateEndpoints.size()); Assertions.assertEquals(peName2, privateEndpoints.get(0).name()); }
class PrivateLinkTests extends ResourceManagerTestProxyTestBase { private AzureResourceManager azureResourceManager; private String rgName; private String saName; private String peName; private String vnName; private String subnetName; private String pecName; private final Region region = Region.US_EAST; private final String vnAddressSpace = "10.0.0.0/28"; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = buildManager(AzureResourceManager.class, httpPipeline, profile); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("sa", 10); vnName = generateRandomResourceName("vn", 10); subnetName = "default"; peName = generateRandomResourceName("pe", 10); pecName = generateRandomResourceName("pec", 10); } @Override protected void cleanUpResources() { try { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (Exception e) { } } @Test @DoNotRecord(skipInPlayback = true) @Test public void testPrivateEndpointE2E() { final boolean validateOnVirtualMachine = true; String vnlName = generateRandomResourceName("vnl", 10); String pdzgName = "default"; String pdzcName = generateRandomResourceName("pdzcName", 20); String pdzcName2 = generateRandomResourceName("pdzcName", 20); String vmName = generateRandomResourceName("vm", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); VirtualMachine virtualMachine = null; if (validateOnVirtualMachine) { virtualMachine = azureResourceManager.virtualMachines().define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet(subnetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testUser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define("privatelink.blob.core.windows.net") .withExistingResourceGroup(rgName) .defineARecordSet(saName) .withIPv4Address(privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0)) .attach() .defineVirtualNetworkLink(vnlName) .withVirtualNetworkId(network.id()) .attach() .create(); PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups().define(pdzgName) .withPrivateDnsZoneConfigure(pdzcName, privateDnsZone.id()) .create(); if (validateOnVirtualMachine) { RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } Assertions.assertEquals(1, privateEndpoint.privateDnsZoneGroups().list().stream().count()); Assertions.assertEquals(pdzgName, privateEndpoint.privateDnsZoneGroups().getById(privateDnsZoneGroup.id()).name()); PrivateDnsZone privateDnsZone2 = azureResourceManager.privateDnsZones().define("link.blob.core.windows.net") .withExistingResourceGroup(rgName) .create(); privateDnsZoneGroup.update() .withoutPrivateDnsZoneConfigure(pdzcName) .withPrivateDnsZoneConfigure(pdzcName2, privateDnsZone2.id()) .apply(); privateEndpoint.privateDnsZoneGroups().deleteById(privateDnsZoneGroup.id()); } @Test public void testStoragePrivateLinkResources() { StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); validatePrivateLinkResource(storageAccount, PrivateLinkSubResourceName.STORAGE_BLOB.toString()); } @Test public void testPrivateEndpointVault() { String vaultName = generateRandomResourceName("vault", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.VAULT; Vault vault = azureResourceManager.vaults().define(vaultName) .withRegion(region) .withNewResourceGroup(rgName) .withEmptyAccessPolicy() .create(); validatePrivateLinkResource(vault, subResourceName.toString()); validateApprovePrivatePrivateEndpointConnection(vault, subResourceName); } @Test public void testPrivateEndpointCosmos() { String cosmosName = generateRandomResourceName("cosmos", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.COSMOS_SQL; CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(cosmosName) .withRegion(region) .withNewResourceGroup(rgName) .withDataModelSql() .withStrongConsistency() .create(); PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(cosmosDBAccount, subResourceName); com.azure.resourcemanager.cosmos.models.PrivateEndpointConnection connection = cosmosDBAccount.listPrivateEndpointConnection().values().iterator().next(); cosmosDBAccount.approvePrivateEndpointConnection(connection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } @Test public void testPrivateEndpointAKS() { String clusterName = generateRandomResourceName("aks", 8); String apName = "ap" + clusterName; String dnsPrefix = "dns" + clusterName; PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.KUBERNETES_MANAGEMENT; KubernetesCluster cluster = azureResourceManager.kubernetesClusters().define(clusterName) .withRegion(region) .withNewResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool(apName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix(dnsPrefix) .enablePrivateCluster() .create(); validatePrivateLinkResource(cluster, subResourceName.toString()); List<PrivateEndpointConnection> connections = cluster.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, connections.size()); PrivateEndpointConnection connection = connections.iterator().next(); Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.APPROVED, connection.privateLinkServiceConnectionState().status()); } @Test public void testPrivateEndpointRedis() { String redisName = generateRandomResourceName("redis", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.REDIS_CACHE; RedisCache redisCache = azureResourceManager.redisCaches().define(redisName) .withRegion(region) .withNewResourceGroup(rgName) .withPremiumSku() .create(); validatePrivateLinkResource(redisCache, subResourceName.toString()); validateListAndApprovePrivatePrivateEndpointConnection(redisCache, subResourceName); } @Test @Disabled("invalid response of WebAppsClient.getPrivateEndpointConnectionListAsync") public void testPrivateEndpointWeb() { String webappName = generateRandomResourceName("webapp", 20); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.WEB_SITES; WebApp webapp = azureResourceManager.webApps().define(webappName) .withRegion(region) .withNewResourceGroup(rgName) .withNewLinuxPlan(PricingTier.PREMIUM_P2V3) .withBuiltInImage(RuntimeStack.JAVA_11_JAVA11) .create(); validatePrivateLinkResource(webapp, subResourceName.toString()); validateListAndApprovePrivatePrivateEndpointConnection(webapp, subResourceName); } private void validatePrivateLinkResource(SupportsListingPrivateLinkResource resource, String requiredGroupId) { PagedIterable<PrivateLinkResource> privateLinkResources = resource.listPrivateLinkResources(); List<PrivateLinkResource> privateLinkResourceList = privateLinkResources.stream().collect(Collectors.toList()); Assertions.assertFalse(privateLinkResourceList.isEmpty()); Assertions.assertTrue(privateLinkResourceList.stream().anyMatch(r -> requiredGroupId.equals(r.groupId()))); } private PrivateEndpoint createPrivateEndpointForManualApproval(Resource resource, PrivateLinkSubResourceName subResourceName) { Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(resource) .withSubResource(subResourceName) .withManualApproval("request message") .attach() .create(); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); return privateEndpoint; } private <T extends Resource & SupportsUpdatingPrivateEndpointConnection> void validateApprovePrivatePrivateEndpointConnection(T resource, PrivateLinkSubResourceName subResourceName) { PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(resource, subResourceName); resource.approvePrivateEndpointConnection(pecName); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } private <T extends Resource & SupportsUpdatingPrivateEndpointConnection & SupportsListingPrivateEndpointConnection> void validateListAndApprovePrivatePrivateEndpointConnection(T resource, PrivateLinkSubResourceName subResourceName) { PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(resource, subResourceName); List<PrivateEndpointConnection> connections = resource.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, connections.size()); PrivateEndpointConnection connection = connections.iterator().next(); resource.approvePrivateEndpointConnection(connection.name()); privateEndpoint.refresh(); int retry = 3; while (retry >= 0 && !"Approved".equals(privateEndpoint.privateLinkServiceConnections().get(pecName).state().status())) { ResourceManagerUtils.sleep(Duration.ofSeconds(30)); privateEndpoint.refresh(); retry--; } Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } private static HashMap<String, String> parseAuthFile(String authFilename) throws Exception { String content = new String(Files.readAllBytes(new File(authFilename).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth; } }
class PrivateLinkTests extends ResourceManagerTestProxyTestBase { private AzureResourceManager azureResourceManager; private String rgName; private String saName; private String peName; private String vnName; private String subnetName; private String pecName; private final Region region = Region.US_EAST; private final String vnAddressSpace = "10.0.0.0/28"; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = buildManager(AzureResourceManager.class, httpPipeline, profile); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("sa", 10); vnName = generateRandomResourceName("vn", 10); subnetName = "default"; peName = generateRandomResourceName("pe", 10); pecName = generateRandomResourceName("pec", 10); } @Override protected void cleanUpResources() { try { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (Exception e) { } } @Test @Test public void testPrivateEndpointE2E() { final boolean validateOnVirtualMachine = true; String vnlName = generateRandomResourceName("vnl", 10); String pdzgName = "default"; String pdzcName = generateRandomResourceName("pdzcName", 20); String pdzcName2 = generateRandomResourceName("pdzcName", 20); String vmName = generateRandomResourceName("vm", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); VirtualMachine virtualMachine = null; if (validateOnVirtualMachine) { virtualMachine = azureResourceManager.virtualMachines().define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet(subnetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testUser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define("privatelink.blob.core.windows.net") .withExistingResourceGroup(rgName) .defineARecordSet(saName) .withIPv4Address(privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0)) .attach() .defineVirtualNetworkLink(vnlName) .withVirtualNetworkId(network.id()) .attach() .create(); PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups().define(pdzgName) .withPrivateDnsZoneConfigure(pdzcName, privateDnsZone.id()) .create(); if (validateOnVirtualMachine) { RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } Assertions.assertEquals(1, privateEndpoint.privateDnsZoneGroups().list().stream().count()); Assertions.assertEquals(pdzgName, privateEndpoint.privateDnsZoneGroups().getById(privateDnsZoneGroup.id()).name()); PrivateDnsZone privateDnsZone2 = azureResourceManager.privateDnsZones().define("link.blob.core.windows.net") .withExistingResourceGroup(rgName) .create(); privateDnsZoneGroup.update() .withoutPrivateDnsZoneConfigure(pdzcName) .withPrivateDnsZoneConfigure(pdzcName2, privateDnsZone2.id()) .apply(); privateEndpoint.privateDnsZoneGroups().deleteById(privateDnsZoneGroup.id()); } @Test public void testStoragePrivateLinkResources() { StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); validatePrivateLinkResource(storageAccount, PrivateLinkSubResourceName.STORAGE_BLOB.toString()); } @Test public void testPrivateEndpointVault() { String vaultName = generateRandomResourceName("vault", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.VAULT; Vault vault = azureResourceManager.vaults().define(vaultName) .withRegion(region) .withNewResourceGroup(rgName) .withEmptyAccessPolicy() .create(); validatePrivateLinkResource(vault, subResourceName.toString()); validateApprovePrivatePrivateEndpointConnection(vault, subResourceName); } @Test public void testPrivateEndpointCosmos() { String cosmosName = generateRandomResourceName("cosmos", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.COSMOS_SQL; CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(cosmosName) .withRegion(region) .withNewResourceGroup(rgName) .withDataModelSql() .withStrongConsistency() .create(); PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(cosmosDBAccount, subResourceName); com.azure.resourcemanager.cosmos.models.PrivateEndpointConnection connection = cosmosDBAccount.listPrivateEndpointConnection().values().iterator().next(); cosmosDBAccount.approvePrivateEndpointConnection(connection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } @Test public void testPrivateEndpointAKS() { String clusterName = generateRandomResourceName("aks", 8); String apName = "ap" + clusterName; String dnsPrefix = "dns" + clusterName; PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.KUBERNETES_MANAGEMENT; KubernetesCluster cluster = azureResourceManager.kubernetesClusters().define(clusterName) .withRegion(region) .withNewResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool(apName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix(dnsPrefix) .enablePrivateCluster() .create(); validatePrivateLinkResource(cluster, subResourceName.toString()); List<PrivateEndpointConnection> connections = cluster.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, connections.size()); PrivateEndpointConnection connection = connections.iterator().next(); Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.APPROVED, connection.privateLinkServiceConnectionState().status()); } @Test public void testPrivateEndpointRedis() { String redisName = generateRandomResourceName("redis", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.REDIS_CACHE; RedisCache redisCache = azureResourceManager.redisCaches().define(redisName) .withRegion(region) .withNewResourceGroup(rgName) .withPremiumSku() .create(); validatePrivateLinkResource(redisCache, subResourceName.toString()); validateListAndApprovePrivatePrivateEndpointConnection(redisCache, subResourceName); } @Test @Disabled("invalid response of WebAppsClient.getPrivateEndpointConnectionListAsync") public void testPrivateEndpointWeb() { String webappName = generateRandomResourceName("webapp", 20); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.WEB_SITES; WebApp webapp = azureResourceManager.webApps().define(webappName) .withRegion(region) .withNewResourceGroup(rgName) .withNewLinuxPlan(PricingTier.PREMIUM_P2V3) .withBuiltInImage(RuntimeStack.JAVA_11_JAVA11) .create(); validatePrivateLinkResource(webapp, subResourceName.toString()); validateListAndApprovePrivatePrivateEndpointConnection(webapp, subResourceName); } private void validatePrivateLinkResource(SupportsListingPrivateLinkResource resource, String requiredGroupId) { PagedIterable<PrivateLinkResource> privateLinkResources = resource.listPrivateLinkResources(); List<PrivateLinkResource> privateLinkResourceList = privateLinkResources.stream().collect(Collectors.toList()); Assertions.assertFalse(privateLinkResourceList.isEmpty()); Assertions.assertTrue(privateLinkResourceList.stream().anyMatch(r -> requiredGroupId.equals(r.groupId()))); } private PrivateEndpoint createPrivateEndpointForManualApproval(Resource resource, PrivateLinkSubResourceName subResourceName) { Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(resource) .withSubResource(subResourceName) .withManualApproval("request message") .attach() .create(); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); return privateEndpoint; } private <T extends Resource & SupportsUpdatingPrivateEndpointConnection> void validateApprovePrivatePrivateEndpointConnection(T resource, PrivateLinkSubResourceName subResourceName) { PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(resource, subResourceName); resource.approvePrivateEndpointConnection(pecName); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } private <T extends Resource & SupportsUpdatingPrivateEndpointConnection & SupportsListingPrivateEndpointConnection> void validateListAndApprovePrivatePrivateEndpointConnection(T resource, PrivateLinkSubResourceName subResourceName) { PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(resource, subResourceName); List<PrivateEndpointConnection> connections = resource.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, connections.size()); PrivateEndpointConnection connection = connections.iterator().next(); resource.approvePrivateEndpointConnection(connection.name()); privateEndpoint.refresh(); int retry = 3; while (retry >= 0 && !"Approved".equals(privateEndpoint.privateLinkServiceConnections().get(pecName).state().status())) { ResourceManagerUtils.sleep(Duration.ofSeconds(30)); privateEndpoint.refresh(); retry--; } Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } private static HashMap<String, String> parseAuthFile(String authFilename) throws Exception { String content = new String(Files.readAllBytes(new File(authFilename).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth; } }
why are we using containerLink and not containerName?
public String toString() { if (this.cosmosContainerIdentities == null || cosmosContainerIdentities.isEmpty()) { return ""; } return String.format( "(containers:%s)(pcrc:%d)(awd:%s)", cosmosContainerIdentities .stream() .map(ci -> String.join( ".", containerIdAccessor.getContainerLink(ci))) .collect(Collectors.joining(";")), numProactiveConnectionRegions, aggressiveWarmupDuration); }
containerIdAccessor.getContainerLink(ci)))
public String toString() { if (this.cosmosContainerIdentities == null || cosmosContainerIdentities.isEmpty()) { return ""; } return String.format( "(containers:%s)(pcrc:%d)(awd:%s)", cosmosContainerIdentities .stream() .map(ci -> String.join( ".", containerIdAccessor.getContainerLink(ci))) .collect(Collectors.joining(";")), numProactiveConnectionRegions, aggressiveWarmupDuration); }
class CosmosContainerProactiveInitConfig { private final static ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor containerIdAccessor = ImplementationBridgeHelpers .CosmosContainerIdentityHelper .getCosmosContainerIdentityAccessor(); private final List<CosmosContainerIdentity> cosmosContainerIdentities; private final Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> containerDirectConnectionMetadataMap; private final int numProactiveConnectionRegions; private final Duration aggressiveWarmupDuration; CosmosContainerProactiveInitConfig( int numProactiveConnectionRegions, Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> containerDirectConnectionMetadataMap, Duration aggressiveWarmupDuration) { this.cosmosContainerIdentities = new ArrayList<>(containerDirectConnectionMetadataMap.keySet()); this.numProactiveConnectionRegions = numProactiveConnectionRegions; this.containerDirectConnectionMetadataMap = containerDirectConnectionMetadataMap; this.aggressiveWarmupDuration = aggressiveWarmupDuration; } /** * Gets the list of container identities. The returned list is protected against modifications. * * @return list of {@link CosmosContainerIdentity} * */ public List<CosmosContainerIdentity> getCosmosContainerIdentities() { return Collections.unmodifiableList(this.cosmosContainerIdentities); } /** * Gets the no. of proactive connection regions * * <p> * Proactive connection regions constitute those regions where replicas of container partitions have connections opened to prior * to performing any workload on the container. This way the latency associated with opening connections * does not impact the latency associated with performing workloads on the container. These connections are * opened synchronously when the {@link CosmosClient}/{@link CosmosAsyncClient} is built. * </p> * <p> * These proactive connection regions are a subset of the preferred regions configured through the {@link CosmosClientBuilder}. The first * {@link CosmosContainerProactiveInitConfig * </p> * <p> * Consider a multi-master account with client configured with preferred regions - "US West" (write-region) and "US East" (write-region) * <br> * 1. If the no. of proactive regions is set to two, connections to "US West" and "US East" are opened proactively. * <br> * 2. If the no. of proactive regions is set to one, connections to "US West" are opened proactively. * <br><br> * Consider a single-master account with client configured with preferred regions - "US West" (read-region), "US East" (read-region) and * "West Europe" (write-region) * <br> * 1. If the no. of proactive regions is set to two, connections to "US West" and "US East" are opened proactively. If your application * has workloads which are write-heavy it is important to prioritize write regions in the list of preferred regions. * </p> * * @return no. of proactive connection regions */ public int getProactiveConnectionRegionsCount() { return numProactiveConnectionRegions; } /** * Gets the duration within which connections will be opened aggressively and in a blocking manner and outside * which connections will be opened defensively and in a non-blocking manner * * @return the aggressive proactive connection establishment duration * */ Duration getAggressiveWarmupDuration() { return this.aggressiveWarmupDuration; } @Override static void initialize() { ImplementationBridgeHelpers.CosmosContainerProactiveInitConfigHelper.setCosmosContainerProactiveInitConfigAccessor(new ImplementationBridgeHelpers.CosmosContainerProactiveInitConfigHelper.CosmosContainerProactiveInitConfigAccessor() { @Override public Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> getContainerPropertiesMap(CosmosContainerProactiveInitConfig cosmosContainerProactiveInitConfig) { return cosmosContainerProactiveInitConfig.containerDirectConnectionMetadataMap; } }); } static { initialize(); } }
class CosmosContainerProactiveInitConfig { private final static ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor containerIdAccessor = ImplementationBridgeHelpers .CosmosContainerIdentityHelper .getCosmosContainerIdentityAccessor(); private final List<CosmosContainerIdentity> cosmosContainerIdentities; private final Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> containerDirectConnectionMetadataMap; private final int numProactiveConnectionRegions; private final Duration aggressiveWarmupDuration; CosmosContainerProactiveInitConfig( int numProactiveConnectionRegions, Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> containerDirectConnectionMetadataMap, Duration aggressiveWarmupDuration) { this.cosmosContainerIdentities = new ArrayList<>(containerDirectConnectionMetadataMap.keySet()); this.numProactiveConnectionRegions = numProactiveConnectionRegions; this.containerDirectConnectionMetadataMap = containerDirectConnectionMetadataMap; this.aggressiveWarmupDuration = aggressiveWarmupDuration; } /** * Gets the list of container identities. The returned list is protected against modifications. * * @return list of {@link CosmosContainerIdentity} * */ public List<CosmosContainerIdentity> getCosmosContainerIdentities() { return Collections.unmodifiableList(this.cosmosContainerIdentities); } /** * Gets the no. of proactive connection regions * * <p> * Proactive connection regions constitute those regions where replicas of container partitions have connections opened to prior * to performing any workload on the container. This way the latency associated with opening connections * does not impact the latency associated with performing workloads on the container. These connections are * opened synchronously when the {@link CosmosClient}/{@link CosmosAsyncClient} is built. * </p> * <p> * These proactive connection regions are a subset of the preferred regions configured through the {@link CosmosClientBuilder}. The first * {@link CosmosContainerProactiveInitConfig * </p> * <p> * Consider a multi-master account with client configured with preferred regions - "US West" (write-region) and "US East" (write-region) * <br> * 1. If the no. of proactive regions is set to two, connections to "US West" and "US East" are opened proactively. * <br> * 2. If the no. of proactive regions is set to one, connections to "US West" are opened proactively. * <br><br> * Consider a single-master account with client configured with preferred regions - "US West" (read-region), "US East" (read-region) and * "West Europe" (write-region) * <br> * 1. If the no. of proactive regions is set to two, connections to "US West" and "US East" are opened proactively. If your application * has workloads which are write-heavy it is important to prioritize write regions in the list of preferred regions. * </p> * * @return no. of proactive connection regions */ public int getProactiveConnectionRegionsCount() { return numProactiveConnectionRegions; } /** * Gets the duration within which connections will be opened aggressively and in a blocking manner and outside * which connections will be opened defensively and in a non-blocking manner * * @return the aggressive proactive connection establishment duration * */ Duration getAggressiveWarmupDuration() { return this.aggressiveWarmupDuration; } @Override static void initialize() { ImplementationBridgeHelpers.CosmosContainerProactiveInitConfigHelper.setCosmosContainerProactiveInitConfigAccessor(new ImplementationBridgeHelpers.CosmosContainerProactiveInitConfigHelper.CosmosContainerProactiveInitConfigAccessor() { @Override public Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> getContainerPropertiesMap(CosmosContainerProactiveInitConfig cosmosContainerProactiveInitConfig) { return cosmosContainerProactiveInitConfig.containerDirectConnectionMetadataMap; } }); } static { initialize(); } }
Here `containerLink` refers to `/dbs/{databaseName}/colls/{containerName}` where `databaseName` and `containerName` are supplied by the client application.
public String toString() { if (this.cosmosContainerIdentities == null || cosmosContainerIdentities.isEmpty()) { return ""; } return String.format( "(containers:%s)(pcrc:%d)(awd:%s)", cosmosContainerIdentities .stream() .map(ci -> String.join( ".", containerIdAccessor.getContainerLink(ci))) .collect(Collectors.joining(";")), numProactiveConnectionRegions, aggressiveWarmupDuration); }
containerIdAccessor.getContainerLink(ci)))
public String toString() { if (this.cosmosContainerIdentities == null || cosmosContainerIdentities.isEmpty()) { return ""; } return String.format( "(containers:%s)(pcrc:%d)(awd:%s)", cosmosContainerIdentities .stream() .map(ci -> String.join( ".", containerIdAccessor.getContainerLink(ci))) .collect(Collectors.joining(";")), numProactiveConnectionRegions, aggressiveWarmupDuration); }
class CosmosContainerProactiveInitConfig { private final static ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor containerIdAccessor = ImplementationBridgeHelpers .CosmosContainerIdentityHelper .getCosmosContainerIdentityAccessor(); private final List<CosmosContainerIdentity> cosmosContainerIdentities; private final Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> containerDirectConnectionMetadataMap; private final int numProactiveConnectionRegions; private final Duration aggressiveWarmupDuration; CosmosContainerProactiveInitConfig( int numProactiveConnectionRegions, Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> containerDirectConnectionMetadataMap, Duration aggressiveWarmupDuration) { this.cosmosContainerIdentities = new ArrayList<>(containerDirectConnectionMetadataMap.keySet()); this.numProactiveConnectionRegions = numProactiveConnectionRegions; this.containerDirectConnectionMetadataMap = containerDirectConnectionMetadataMap; this.aggressiveWarmupDuration = aggressiveWarmupDuration; } /** * Gets the list of container identities. The returned list is protected against modifications. * * @return list of {@link CosmosContainerIdentity} * */ public List<CosmosContainerIdentity> getCosmosContainerIdentities() { return Collections.unmodifiableList(this.cosmosContainerIdentities); } /** * Gets the no. of proactive connection regions * * <p> * Proactive connection regions constitute those regions where replicas of container partitions have connections opened to prior * to performing any workload on the container. This way the latency associated with opening connections * does not impact the latency associated with performing workloads on the container. These connections are * opened synchronously when the {@link CosmosClient}/{@link CosmosAsyncClient} is built. * </p> * <p> * These proactive connection regions are a subset of the preferred regions configured through the {@link CosmosClientBuilder}. The first * {@link CosmosContainerProactiveInitConfig * </p> * <p> * Consider a multi-master account with client configured with preferred regions - "US West" (write-region) and "US East" (write-region) * <br> * 1. If the no. of proactive regions is set to two, connections to "US West" and "US East" are opened proactively. * <br> * 2. If the no. of proactive regions is set to one, connections to "US West" are opened proactively. * <br><br> * Consider a single-master account with client configured with preferred regions - "US West" (read-region), "US East" (read-region) and * "West Europe" (write-region) * <br> * 1. If the no. of proactive regions is set to two, connections to "US West" and "US East" are opened proactively. If your application * has workloads which are write-heavy it is important to prioritize write regions in the list of preferred regions. * </p> * * @return no. of proactive connection regions */ public int getProactiveConnectionRegionsCount() { return numProactiveConnectionRegions; } /** * Gets the duration within which connections will be opened aggressively and in a blocking manner and outside * which connections will be opened defensively and in a non-blocking manner * * @return the aggressive proactive connection establishment duration * */ Duration getAggressiveWarmupDuration() { return this.aggressiveWarmupDuration; } @Override static void initialize() { ImplementationBridgeHelpers.CosmosContainerProactiveInitConfigHelper.setCosmosContainerProactiveInitConfigAccessor(new ImplementationBridgeHelpers.CosmosContainerProactiveInitConfigHelper.CosmosContainerProactiveInitConfigAccessor() { @Override public Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> getContainerPropertiesMap(CosmosContainerProactiveInitConfig cosmosContainerProactiveInitConfig) { return cosmosContainerProactiveInitConfig.containerDirectConnectionMetadataMap; } }); } static { initialize(); } }
class CosmosContainerProactiveInitConfig { private final static ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor containerIdAccessor = ImplementationBridgeHelpers .CosmosContainerIdentityHelper .getCosmosContainerIdentityAccessor(); private final List<CosmosContainerIdentity> cosmosContainerIdentities; private final Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> containerDirectConnectionMetadataMap; private final int numProactiveConnectionRegions; private final Duration aggressiveWarmupDuration; CosmosContainerProactiveInitConfig( int numProactiveConnectionRegions, Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> containerDirectConnectionMetadataMap, Duration aggressiveWarmupDuration) { this.cosmosContainerIdentities = new ArrayList<>(containerDirectConnectionMetadataMap.keySet()); this.numProactiveConnectionRegions = numProactiveConnectionRegions; this.containerDirectConnectionMetadataMap = containerDirectConnectionMetadataMap; this.aggressiveWarmupDuration = aggressiveWarmupDuration; } /** * Gets the list of container identities. The returned list is protected against modifications. * * @return list of {@link CosmosContainerIdentity} * */ public List<CosmosContainerIdentity> getCosmosContainerIdentities() { return Collections.unmodifiableList(this.cosmosContainerIdentities); } /** * Gets the no. of proactive connection regions * * <p> * Proactive connection regions constitute those regions where replicas of container partitions have connections opened to prior * to performing any workload on the container. This way the latency associated with opening connections * does not impact the latency associated with performing workloads on the container. These connections are * opened synchronously when the {@link CosmosClient}/{@link CosmosAsyncClient} is built. * </p> * <p> * These proactive connection regions are a subset of the preferred regions configured through the {@link CosmosClientBuilder}. The first * {@link CosmosContainerProactiveInitConfig * </p> * <p> * Consider a multi-master account with client configured with preferred regions - "US West" (write-region) and "US East" (write-region) * <br> * 1. If the no. of proactive regions is set to two, connections to "US West" and "US East" are opened proactively. * <br> * 2. If the no. of proactive regions is set to one, connections to "US West" are opened proactively. * <br><br> * Consider a single-master account with client configured with preferred regions - "US West" (read-region), "US East" (read-region) and * "West Europe" (write-region) * <br> * 1. If the no. of proactive regions is set to two, connections to "US West" and "US East" are opened proactively. If your application * has workloads which are write-heavy it is important to prioritize write regions in the list of preferred regions. * </p> * * @return no. of proactive connection regions */ public int getProactiveConnectionRegionsCount() { return numProactiveConnectionRegions; } /** * Gets the duration within which connections will be opened aggressively and in a blocking manner and outside * which connections will be opened defensively and in a non-blocking manner * * @return the aggressive proactive connection establishment duration * */ Duration getAggressiveWarmupDuration() { return this.aggressiveWarmupDuration; } @Override static void initialize() { ImplementationBridgeHelpers.CosmosContainerProactiveInitConfigHelper.setCosmosContainerProactiveInitConfigAccessor(new ImplementationBridgeHelpers.CosmosContainerProactiveInitConfigHelper.CosmosContainerProactiveInitConfigAccessor() { @Override public Map<CosmosContainerIdentity, ContainerDirectConnectionMetadata> getContainerPropertiesMap(CosmosContainerProactiveInitConfig cosmosContainerProactiveInitConfig) { return cosmosContainerProactiveInitConfig.containerDirectConnectionMetadataMap; } }); } static { initialize(); } }
nit: period goes on next line as well.
PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder. logPii(options.isSupportLoggingEnabled()). authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; }
logPii(options.isSupportLoggingEnabled()).
PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder. logPii(options.isSupportLoggingEnabled()). authority(authorityUrl). instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder. validateAuthority(false). logPii(options.isSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl). logPii(options.isSupportLoggingEnabled()). instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azdCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError( new IllegalStateException( "A Safe Working directory could not be" + " found to execute Azure Developer CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(options.getClientOptions(), httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); if (options.getClientOptions() != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); options.getClientOptions().getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder .logPii(options.isSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder .validateAuthority(false) .logPii(options.isSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl) .logPii(options.isSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azdCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError( new IllegalStateException( "A Safe Working directory could not be" + " found to execute Azure Developer CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(options.getClientOptions(), httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); if (options.getClientOptions() != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); options.getClientOptions().getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } }
Planning on keeping both.
public AnalyzeDocumentOptions setDocumentAnalysisFeatures(List<DocumentAnalysisFeature> documentAnalysisFeatures) { this.documentAnalysisFeatures = documentAnalysisFeatures; return this; }
}
public AnalyzeDocumentOptions setDocumentAnalysisFeatures(List<DocumentAnalysisFeature> documentAnalysisFeatures) { this.documentAnalysisFeatures = documentAnalysisFeatures; return this; }
class AnalyzeDocumentOptions { private List<String> pages; private String locale; private List<DocumentAnalysisFeature> documentAnalysisFeatures; /** * Get the custom page numbers for multi-page documents(PDF/TIFF). Input the number of the * pages you want to get the recognized result for. * <p>For a range of pages, use a hyphen, ex - ["1-3"]. Separate each page or a page * range with a comma, ex - ["1-3", 4].</p> * * @return the list of custom page numbers for a multi page document. */ public List<String> getPages() { return pages; } /** * Set the custom page numbers for multi-page documents(PDF/TIFF). Input the number of the * pages you want to get the recognized result for. * <p>For a range of pages, use a hyphen, ex - ["1-3"]. Separate each page or a page * range with a comma, ex - ["1-3", 4].</p> * * @param pages the custom page numbers value to set. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setPages(List<String> pages) { this.pages = pages; return this; } /** * Get the locale hint for text recognition and document analysis. * Value may contain only the language code (ex. \"en\", \"fr\") or BCP 47 language tag (ex. \"en-US\"). * * @return the locale value. */ public String getLocale() { return locale; } /** * Set the locale value. * Supported locales include: en-AU, en-CA, en-GB, en-IN, en-US. * * @param locale the locale value to set. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setLocale(String locale) { this.locale = locale; return this; } /** * Get the list of optional analysis features. * @return List of optional analysis features. */ public List<DocumentAnalysisFeature> getDocumentAnalysisFeatures() { return documentAnalysisFeatures; } /** * Set the list of optional analysis features. * @param documentAnalysisFeatures List of optional analysis features. * @return the updated {@code AnalyzeDocumentOptions} value. */ /** * Set optional analysis features. * @param documentAnalysisFeatures List of optional analysis features. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setDocumentAnalysisFeatures(DocumentAnalysisFeature... documentAnalysisFeatures) { if (documentAnalysisFeatures != null) { this.documentAnalysisFeatures = Arrays.asList(documentAnalysisFeatures); } return this; } }
class AnalyzeDocumentOptions { private List<String> pages; private String locale; private List<DocumentAnalysisFeature> documentAnalysisFeatures; /** * Get the custom page numbers for multi-page documents(PDF/TIFF). Input the number of the * pages you want to get the recognized result for. * <p>For a range of pages, use a hyphen, ex - ["1-3"]. Separate each page or a page * range with a comma, ex - ["1-3", 4].</p> * * @return the list of custom page numbers for a multi page document. */ public List<String> getPages() { return pages; } /** * Set the custom page numbers for multi-page documents(PDF/TIFF). Input the number of the * pages you want to get the recognized result for. * <p>For a range of pages, use a hyphen, ex - ["1-3"]. Separate each page or a page * range with a comma, ex - ["1-3", 4].</p> * * @param pages the custom page numbers value to set. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setPages(List<String> pages) { this.pages = pages; return this; } /** * Get the locale hint for text recognition and document analysis. * Value may contain only the language code (ex. \"en\", \"fr\") or BCP 47 language tag (ex. \"en-US\"). * * @return the locale value. */ public String getLocale() { return locale; } /** * Set the locale value. * Supported locales include: en-AU, en-CA, en-GB, en-IN, en-US. * * @param locale the locale value to set. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setLocale(String locale) { this.locale = locale; return this; } /** * Get the list of optional analysis features. * @return List of optional analysis features. */ public List<DocumentAnalysisFeature> getDocumentAnalysisFeatures() { return documentAnalysisFeatures; } /** * Set the list of optional analysis features. * @param documentAnalysisFeatures List of optional analysis features. * @return the updated {@code AnalyzeDocumentOptions} value. */ /** * Set optional analysis features. * @param documentAnalysisFeatures List of optional analysis features. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setDocumentAnalysisFeatures(DocumentAnalysisFeature... documentAnalysisFeatures) { if (documentAnalysisFeatures != null) { this.documentAnalysisFeatures = Arrays.asList(documentAnalysisFeatures); } return this; } }
Should we remove this method since we add the new method?`setDocumentAnalysisFeatures(DocumentAnalysisFeature... documentAnalysisFeatures)` And the method is still in beta
public AnalyzeDocumentOptions setDocumentAnalysisFeatures(List<DocumentAnalysisFeature> documentAnalysisFeatures) { this.documentAnalysisFeatures = documentAnalysisFeatures; return this; }
}
public AnalyzeDocumentOptions setDocumentAnalysisFeatures(List<DocumentAnalysisFeature> documentAnalysisFeatures) { this.documentAnalysisFeatures = documentAnalysisFeatures; return this; }
class AnalyzeDocumentOptions { private List<String> pages; private String locale; private List<DocumentAnalysisFeature> documentAnalysisFeatures; /** * Get the custom page numbers for multi-page documents(PDF/TIFF). Input the number of the * pages you want to get the recognized result for. * <p>For a range of pages, use a hyphen, ex - ["1-3"]. Separate each page or a page * range with a comma, ex - ["1-3", 4].</p> * * @return the list of custom page numbers for a multi page document. */ public List<String> getPages() { return pages; } /** * Set the custom page numbers for multi-page documents(PDF/TIFF). Input the number of the * pages you want to get the recognized result for. * <p>For a range of pages, use a hyphen, ex - ["1-3"]. Separate each page or a page * range with a comma, ex - ["1-3", 4].</p> * * @param pages the custom page numbers value to set. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setPages(List<String> pages) { this.pages = pages; return this; } /** * Get the locale hint for text recognition and document analysis. * Value may contain only the language code (ex. \"en\", \"fr\") or BCP 47 language tag (ex. \"en-US\"). * * @return the locale value. */ public String getLocale() { return locale; } /** * Set the locale value. * Supported locales include: en-AU, en-CA, en-GB, en-IN, en-US. * * @param locale the locale value to set. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setLocale(String locale) { this.locale = locale; return this; } /** * Get the list of optional analysis features. * @return List of optional analysis features. */ public List<DocumentAnalysisFeature> getDocumentAnalysisFeatures() { return documentAnalysisFeatures; } /** * Set the list of optional analysis features. * @param documentAnalysisFeatures List of optional analysis features. * @return the updated {@code AnalyzeDocumentOptions} value. */ /** * Set optional analysis features. * @param documentAnalysisFeatures List of optional analysis features. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setDocumentAnalysisFeatures(DocumentAnalysisFeature... documentAnalysisFeatures) { if (documentAnalysisFeatures != null) { this.documentAnalysisFeatures = Arrays.asList(documentAnalysisFeatures); } return this; } }
class AnalyzeDocumentOptions { private List<String> pages; private String locale; private List<DocumentAnalysisFeature> documentAnalysisFeatures; /** * Get the custom page numbers for multi-page documents(PDF/TIFF). Input the number of the * pages you want to get the recognized result for. * <p>For a range of pages, use a hyphen, ex - ["1-3"]. Separate each page or a page * range with a comma, ex - ["1-3", 4].</p> * * @return the list of custom page numbers for a multi page document. */ public List<String> getPages() { return pages; } /** * Set the custom page numbers for multi-page documents(PDF/TIFF). Input the number of the * pages you want to get the recognized result for. * <p>For a range of pages, use a hyphen, ex - ["1-3"]. Separate each page or a page * range with a comma, ex - ["1-3", 4].</p> * * @param pages the custom page numbers value to set. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setPages(List<String> pages) { this.pages = pages; return this; } /** * Get the locale hint for text recognition and document analysis. * Value may contain only the language code (ex. \"en\", \"fr\") or BCP 47 language tag (ex. \"en-US\"). * * @return the locale value. */ public String getLocale() { return locale; } /** * Set the locale value. * Supported locales include: en-AU, en-CA, en-GB, en-IN, en-US. * * @param locale the locale value to set. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setLocale(String locale) { this.locale = locale; return this; } /** * Get the list of optional analysis features. * @return List of optional analysis features. */ public List<DocumentAnalysisFeature> getDocumentAnalysisFeatures() { return documentAnalysisFeatures; } /** * Set the list of optional analysis features. * @param documentAnalysisFeatures List of optional analysis features. * @return the updated {@code AnalyzeDocumentOptions} value. */ /** * Set optional analysis features. * @param documentAnalysisFeatures List of optional analysis features. * @return the updated {@code AnalyzeDocumentOptions} value. */ public AnalyzeDocumentOptions setDocumentAnalysisFeatures(DocumentAnalysisFeature... documentAnalysisFeatures) { if (documentAnalysisFeatures != null) { this.documentAnalysisFeatures = Arrays.asList(documentAnalysisFeatures); } return this; } }
Can we just check that the message is not empty? If we change our error message strings on Rooms service, it would cause these tests to fail unnecessarily
public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid format for communication identifier.", exception.getValue().getError().getMessage()); }
assertEquals("Invalid format for communication identifier.", exception.getValue().getError().getMessage());
public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid room ID.", exception.getValue().getError().getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid value for the Participants.", exception.getValue().getError().getMessage()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
Same here
public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid room ID.", exception.getValue().getError().getMessage()); }
assertEquals("Invalid room ID.", exception.getValue().getError().getMessage());
public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid format for communication identifier.", exception.getValue().getError().getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid value for the Participants.", exception.getValue().getError().getMessage()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
Same here
public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid value for the Participants.", exception.getValue().getError().getMessage()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); }
assertEquals("Invalid value for the Participants.", exception.getValue().getError().getMessage());
public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid format for communication identifier.", exception.getValue().getError().getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid room ID.", exception.getValue().getError().getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
Updated now
public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid format for communication identifier.", exception.getValue().getError().getMessage()); }
assertEquals("Invalid format for communication identifier.", exception.getValue().getError().getMessage());
public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid room ID.", exception.getValue().getError().getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid value for the Participants.", exception.getValue().getError().getMessage()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
updated
public AnalyzeImageResult analyzeImage(BinaryData content) { RequestOptions requestOptions = new RequestOptions(); AnalyzeImageOptions body = new AnalyzeImageOptions(new ContentSafetyImageData().setContent(content)); return analyzeImageWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeImageResult.class); }
.toObject(AnalyzeImageResult.class);
public AnalyzeImageResult analyzeImage(BinaryData content) { AnalyzeImageOptions body = new AnalyzeImageOptions(new ContentSafetyImageData().setContent(content)); return analyzeImage(body); }
class ContentSafetyClient { @Generated private final ContentSafetyClientImpl serviceClient; /** * Initializes an instance of ContentSafetyClient class. * * @param serviceClient the service client implementation. */ @Generated ContentSafetyClient(ContentSafetyClientImpl serviceClient) { this.serviceClient = serviceClient; } /** * Analyze Text * * <p>A synchronous API for the analysis of potentially harmful text content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * text: String (Required) * categories (Optional): [ * String(Hate/SelfHarm/Sexual/Violence) (Optional) * ] * blocklistNames (Optional): [ * String (Optional) * ] * haltOnBlocklistHit: Boolean (Optional) * outputType: String(FourSeverityLevels/EightSeverityLevels) (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * blocklistsMatch (Optional): [ * (Optional){ * blocklistName: String (Required) * blocklistItemId: String (Required) * blocklistItemText: String (Required) * } * ] * categoriesAnalysis (Required): [ * (Required){ * category: String(Hate/SelfHarm/Sexual/Violence) (Required) * severity: Integer (Optional) * } * ] * } * }</pre> * * @param body The text analysis request. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the text analysis response along with {@link Response}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Response<BinaryData> analyzeTextWithResponse(BinaryData body, RequestOptions requestOptions) { return this.serviceClient.analyzeTextWithResponse(body, requestOptions); } /** * Analyze Image * * <p>A synchronous API for the analysis of potentially harmful image content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * image (Required): { * content: byte[] (Optional) * blobUrl: String (Optional) * } * categories (Optional): [ * String(Hate/SelfHarm/Sexual/Violence) (Optional) * ] * outputType: String(FourSeverityLevels) (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * categoriesAnalysis (Required): [ * (Required){ * category: String(Hate/SelfHarm/Sexual/Violence) (Required) * severity: Integer (Optional) * } * ] * } * }</pre> * * @param body The image analysis request. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the image analysis response along with {@link Response}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Response<BinaryData> analyzeImageWithResponse(BinaryData body, RequestOptions requestOptions) { return this.serviceClient.analyzeImageWithResponse(body, requestOptions); } /** * Analyze Text * * <p>A synchronous API for the analysis of potentially harmful text content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param body The text analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the text analysis response. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeTextResult analyzeText(AnalyzeTextOptions body) { RequestOptions requestOptions = new RequestOptions(); return analyzeTextWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeTextResult.class); } /** * Analyze Text * * <p>A synchronous API for the analysis of potentially harmful text content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param text The text. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the text analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeTextResult analyzeText(String text) { RequestOptions requestOptions = new RequestOptions(); AnalyzeTextOptions body = new AnalyzeTextOptions(text); return analyzeTextWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeTextResult.class); } /** * Analyze Image * * <p>A synchronous API for the analysis of potentially harmful image content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param body The image analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeImageResult analyzeImage(AnalyzeImageOptions body) { RequestOptions requestOptions = new RequestOptions(); return analyzeImageWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeImageResult.class); } /** * Analyze Image * * <p>A synchronous API for the analysis of potentially harmful image content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param blobUri A string of blob url. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeImageResult analyzeImage(String blobUri) { RequestOptions requestOptions = new RequestOptions(); AnalyzeImageOptions body = new AnalyzeImageOptions(new ContentSafetyImageData().setBlobUri(blobUri)); return analyzeImageWithResponse(BinaryData.fromObject(body), requestOptions) .getValue() .toObject(AnalyzeImageResult.class); } /** * Analyze Image * * <p>A synchronous API for the analysis of potentially harmful image content. Currently, it supports four * categories: Hate, SelfHarm, Sexual, and Violence. * * @param content A list of bytes of content. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) }
class ContentSafetyClient { @Generated private final ContentSafetyClientImpl serviceClient; /** * Initializes an instance of ContentSafetyClient class. * * @param serviceClient the service client implementation. */ @Generated ContentSafetyClient(ContentSafetyClientImpl serviceClient) { this.serviceClient = serviceClient; } /** * Analyze Text * * A synchronous API for the analysis of potentially harmful text content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * <p> * <strong>Request Body Schema</strong> * </p> * <pre>{@code * { * text: String (Required) * categories (Optional): [ * String(Hate/SelfHarm/Sexual/Violence) (Optional) * ] * blocklistNames (Optional): [ * String (Optional) * ] * haltOnBlocklistHit: Boolean (Optional) * outputType: String(FourSeverityLevels/EightSeverityLevels) (Optional) * } * }</pre> * <p> * <strong>Response Body Schema</strong> * </p> * <pre>{@code * { * blocklistsMatch (Optional): [ * (Optional){ * blocklistName: String (Required) * blocklistItemId: String (Required) * blocklistItemText: String (Required) * } * ] * categoriesAnalysis (Required): [ * (Required){ * category: String(Hate/SelfHarm/Sexual/Violence) (Required) * severity: Integer (Optional) * } * ] * } * }</pre> * * @param options The text analysis request. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the text analysis response along with {@link Response}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Response<BinaryData> analyzeTextWithResponse(BinaryData options, RequestOptions requestOptions) { return this.serviceClient.analyzeTextWithResponse(options, requestOptions); } /** * Analyze Image * * A synchronous API for the analysis of potentially harmful image content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * <p> * <strong>Request Body Schema</strong> * </p> * <pre>{@code * { * image (Required): { * content: byte[] (Optional) * blobUrl: String (Optional) * } * categories (Optional): [ * String(Hate/SelfHarm/Sexual/Violence) (Optional) * ] * outputType: String(FourSeverityLevels) (Optional) * } * }</pre> * <p> * <strong>Response Body Schema</strong> * </p> * <pre>{@code * { * categoriesAnalysis (Required): [ * (Required){ * category: String(Hate/SelfHarm/Sexual/Violence) (Required) * severity: Integer (Optional) * } * ] * } * }</pre> * * @param options The image analysis request. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the image analysis response along with {@link Response}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Response<BinaryData> analyzeImageWithResponse(BinaryData options, RequestOptions requestOptions) { return this.serviceClient.analyzeImageWithResponse(options, requestOptions); } /** * Analyze Text * * A synchronous API for the analysis of potentially harmful text content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param options The text analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the text analysis response. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeTextResult analyzeText(AnalyzeTextOptions options) { RequestOptions requestOptions = new RequestOptions(); return analyzeTextWithResponse(BinaryData.fromObject(options), requestOptions).getValue() .toObject(AnalyzeTextResult.class); } /** * Analyze Text * * A synchronous API for the analysis of potentially harmful text content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param text The text analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the text analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeTextResult analyzeText(String text) { AnalyzeTextOptions options = new AnalyzeTextOptions(text); return analyzeText(options); } /** * Analyze Image * * A synchronous API for the analysis of potentially harmful image content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param options The image analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeImageResult analyzeImage(AnalyzeImageOptions options) { RequestOptions requestOptions = new RequestOptions(); return analyzeImageWithResponse(BinaryData.fromObject(options), requestOptions).getValue() .toObject(AnalyzeImageResult.class); } /** * Analyze Image * * A synchronous API for the analysis of potentially harmful image content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param blobUrl The image analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) public AnalyzeImageResult analyzeImage(String blobUrl) { AnalyzeImageOptions body = new AnalyzeImageOptions(new ContentSafetyImageData().setBlobUrl(blobUrl)); return analyzeImage(body); } /** * Analyze Image * * A synchronous API for the analysis of potentially harmful image content. Currently, it supports four categories: * Hate, SelfHarm, Sexual, and Violence. * * @param content The image analysis request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the image analysis response. */ @ServiceMethod(returns = ReturnType.SINGLE) }
Updated now
public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid room ID.", exception.getValue().getError().getMessage()); }
assertEquals("Invalid room ID.", exception.getValue().getError().getMessage());
public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid format for communication identifier.", exception.getValue().getError().getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid value for the Participants.", exception.getValue().getError().getMessage()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
Updated
public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid value for the Participants.", exception.getValue().getError().getMessage()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); }
assertEquals("Invalid value for the Participants.", exception.getValue().getError().getMessage());
public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants, null).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId, null); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<Response<RemoveParticipantsResult>> removeParticipantResponse = roomsAsyncClient.removeParticipantsWithResponse(roomId, participantsIdentifiersForParticipants, null); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 200); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); List<CommunicationIdentifier> participantsIdentifiersForNonExistentParticipant = Arrays .asList(new CommunicationUserIdentifier("8:acs:nonExistentParticipant")); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForNonExistentParticipant).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); Mono<RemoveParticipantsResult> removeParticipantResponse2 = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse5 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse5.count()) .expectNext(1L) .verifyComplete(); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid format for communication identifier.", exception.getValue().getError().getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertEquals("Invalid room ID.", exception.getValue().getError().getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId, null); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithNoAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithNoAttributes"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions(); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<CommunicationRoom> response2 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response3 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(result3.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyParticipantAttributes"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilInPast"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL.minusMonths(6)) .setParticipants(participants); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithOnlyValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(createRoomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomWithBadParticipantMri(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomWithBadParticipantMri"); assertNotNull(roomsAsyncClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); CreateRoomOptions roomOptions = new CreateRoomOptions() .setParticipants(badParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.createRoomWithResponse(roomOptions, Context.NONE).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsAsyncClient); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.getRoom(nonExistRoomId).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); assertFalse(exception.getValue().getError().getMessage().isEmpty()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions, null); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions, null).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Void> response5 = roomsAsyncClient.deleteRoom(roomId, null); StepVerifier.create(response5).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidFromGreaterThan180(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidFromGreaterThan180"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomValidUntilInPast(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomValidUntilInPast"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomWithInvalidRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateRoomWithInvalidRoomId"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(createRoomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.minusMonths(6)) .setValidUntil(VALID_FROM.minusMonths(3)); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.updateRoom(roomId, updateRoomOptions).block(); }); assertEquals("BadRequest", exception.getValue().getError().getCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateInvalidParticipants(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateInvalidParticipants"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI")); RoomParticipant secondParticipant = new RoomParticipant(new CommunicationUserIdentifier("badMRI2")); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CommunicationErrorResponseException exception = assertThrows(CommunicationErrorResponseException.class, () -> { roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); }); assertEquals(400, exception.getResponse().getStatusCode()); Mono<Response<Void>> response2 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(null); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate, null); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); Mono<Response<Void>> response4 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
If total is Long, desiredVMCount should also be long.
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final int desiredVMCount = 6; final Region region = Region.US_EAST; String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); List<String> vmNameList = new ArrayList<>(); Long total = 0L; Boolean rtnValue = false; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { String vmName = Utils.randomResourceName(azureResourceManager, "javascvm", 15); vmNameList.add("'".concat(vmName).concat("'")); azureResourceManager.virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0." + i + ".0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1 , CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to batch query the status(the number of provisioningState=Succeeded)."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Succeeded')) ") .append("| project name,id,type,location,subscriptionId,resourceGroup,tags"); while (total < desiredVMCount) { total = resourceGraphManager.resourceProviders() .resources( new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) ) .totalRecords(); if (total < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } rtnValue = true; } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return rtnValue; }
for (int i = 0; i < desiredVMCount; i++) {
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Integer desiredVMCount = 6; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); Integer succeededTotal = 0; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { azureResourceManager.virtualMachines() .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to query the count number for each [provisioningState]."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name contains 'javascvm') ") .append("| extend provisioningState = case(") .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") .append("properties['provisioningState'] =~ 'Accepted','Accepted',") .append("properties['provisioningState'] =~ 'Running','Running',") .append("properties['provisioningState'] =~ 'Ready','Ready',") .append("properties['provisioningState'] =~ 'Creating','Creating',") .append("properties['provisioningState'] =~ 'Created','Created',") .append("properties['provisioningState'] =~ 'Deleting','Deleting',") .append("properties['provisioningState'] =~ 'Deleted','Deleted',") .append("properties['provisioningState'] =~ 'Canceled','Canceled',") .append("properties['provisioningState'] =~ 'Failed','Failed',") .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") .append("properties['provisioningState'] =~ 'Updating','Updating',") .append("properties['provisioningState']) ") .append("| summarize count=count() by provisioningState"); while (succeededTotal < desiredVMCount) { Integer creatingTotal = 0; Integer updatingTotal = 0; Integer failedTotal = 0; Integer otherTotal = 0; succeededTotal = 0; QueryResponse queryResponse = resourceGraphManager.resourceProviders() .resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); List<TotalResult> totalResultList = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference<List<TotalResult>>() {}); for (TotalResult totalResult : totalResultList) { switch (totalResult.getProvisioningState()) { case "Creating": creatingTotal = totalResult.getCount(); break; case "Succeeded": succeededTotal = totalResult.getCount(); break; case "Updating": updatingTotal = totalResult.getCount(); break; case "Failed": failedTotal = totalResult.getCount(); break; default: otherTotal += totalResult.getCount(); break; } } System.out.println(new StringBuilder() .append("\n\tThe total number of Creating : ").append(creatingTotal) .append("\n\tThe total number of Updating : ").append(updatingTotal) .append("\n\tThe total number of Failed : ").append(failedTotal) .append("\n\tThe total number of Succeeded : ").append(succeededTotal) .append("\n\tThe total number of Other Status : ").append(otherTotal)); if (failedTotal > 0) { break; } else if (succeededTotal < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return succeededTotal.equals(desiredVMCount); }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} private static class TotalResult { private String provisioningState; private Integer count; public String getProvisioningState() { return provisioningState; } public void setProvisioningState(String provisioningState) { this.provisioningState = provisioningState; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } }
Fixed in the new version
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final int desiredVMCount = 6; final Region region = Region.US_EAST; String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); List<String> vmNameList = new ArrayList<>(); Long total = 0L; Boolean rtnValue = false; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { String vmName = Utils.randomResourceName(azureResourceManager, "javascvm", 15); vmNameList.add("'".concat(vmName).concat("'")); azureResourceManager.virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0." + i + ".0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1 , CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to batch query the status(the number of provisioningState=Succeeded)."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Succeeded')) ") .append("| project name,id,type,location,subscriptionId,resourceGroup,tags"); while (total < desiredVMCount) { total = resourceGraphManager.resourceProviders() .resources( new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) ) .totalRecords(); if (total < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } rtnValue = true; } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return rtnValue; }
for (int i = 0; i < desiredVMCount; i++) {
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Integer desiredVMCount = 6; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); Integer succeededTotal = 0; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { azureResourceManager.virtualMachines() .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to query the count number for each [provisioningState]."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name contains 'javascvm') ") .append("| extend provisioningState = case(") .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") .append("properties['provisioningState'] =~ 'Accepted','Accepted',") .append("properties['provisioningState'] =~ 'Running','Running',") .append("properties['provisioningState'] =~ 'Ready','Ready',") .append("properties['provisioningState'] =~ 'Creating','Creating',") .append("properties['provisioningState'] =~ 'Created','Created',") .append("properties['provisioningState'] =~ 'Deleting','Deleting',") .append("properties['provisioningState'] =~ 'Deleted','Deleted',") .append("properties['provisioningState'] =~ 'Canceled','Canceled',") .append("properties['provisioningState'] =~ 'Failed','Failed',") .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") .append("properties['provisioningState'] =~ 'Updating','Updating',") .append("properties['provisioningState']) ") .append("| summarize count=count() by provisioningState"); while (succeededTotal < desiredVMCount) { Integer creatingTotal = 0; Integer updatingTotal = 0; Integer failedTotal = 0; Integer otherTotal = 0; succeededTotal = 0; QueryResponse queryResponse = resourceGraphManager.resourceProviders() .resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); List<TotalResult> totalResultList = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference<List<TotalResult>>() {}); for (TotalResult totalResult : totalResultList) { switch (totalResult.getProvisioningState()) { case "Creating": creatingTotal = totalResult.getCount(); break; case "Succeeded": succeededTotal = totalResult.getCount(); break; case "Updating": updatingTotal = totalResult.getCount(); break; case "Failed": failedTotal = totalResult.getCount(); break; default: otherTotal += totalResult.getCount(); break; } } System.out.println(new StringBuilder() .append("\n\tThe total number of Creating : ").append(creatingTotal) .append("\n\tThe total number of Updating : ").append(updatingTotal) .append("\n\tThe total number of Failed : ").append(failedTotal) .append("\n\tThe total number of Succeeded : ").append(succeededTotal) .append("\n\tThe total number of Other Status : ").append(otherTotal)); if (failedTotal > 0) { break; } else if (succeededTotal < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return succeededTotal.equals(desiredVMCount); }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} private static class TotalResult { private String provisioningState; private Integer count; public String getProvisioningState() { return provisioningState; } public void setProvisioningState(String provisioningState) { this.provisioningState = provisioningState; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } }
For a more realistic sample, could you see if you can first create a virtual network (before the loop), and put all these VM into that virtual network (via `withExistingPrimaryNetwork`)? --- Rest looks good.
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Long desiredVMCount = 6L; final Region region = Region.US_EAST; String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); List<String> vmNameList = new ArrayList<>(); Long total = 0L; Boolean rtnValue = false; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { String vmName = Utils.randomResourceName(azureResourceManager, "javascvm", 15); vmNameList.add("'".concat(vmName).concat("'")); azureResourceManager.virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0." + i + ".0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to batch query the status(the number of provisioningState=Succeeded)."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Succeeded')) ") .append("| project name,id,type,location,subscriptionId,resourceGroup,tags"); while (total < desiredVMCount) { total = resourceGraphManager.resourceProviders() .resources( new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) ) .totalRecords(); if (total < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } rtnValue = true; } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return rtnValue; }
.withNewPrimaryNetwork("10.0." + i + ".0/28")
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Integer desiredVMCount = 6; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); Integer succeededTotal = 0; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { azureResourceManager.virtualMachines() .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to query the count number for each [provisioningState]."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name contains 'javascvm') ") .append("| extend provisioningState = case(") .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") .append("properties['provisioningState'] =~ 'Accepted','Accepted',") .append("properties['provisioningState'] =~ 'Running','Running',") .append("properties['provisioningState'] =~ 'Ready','Ready',") .append("properties['provisioningState'] =~ 'Creating','Creating',") .append("properties['provisioningState'] =~ 'Created','Created',") .append("properties['provisioningState'] =~ 'Deleting','Deleting',") .append("properties['provisioningState'] =~ 'Deleted','Deleted',") .append("properties['provisioningState'] =~ 'Canceled','Canceled',") .append("properties['provisioningState'] =~ 'Failed','Failed',") .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") .append("properties['provisioningState'] =~ 'Updating','Updating',") .append("properties['provisioningState']) ") .append("| summarize count=count() by provisioningState"); while (succeededTotal < desiredVMCount) { Integer creatingTotal = 0; Integer updatingTotal = 0; Integer failedTotal = 0; Integer otherTotal = 0; succeededTotal = 0; QueryResponse queryResponse = resourceGraphManager.resourceProviders() .resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); List<TotalResult> totalResultList = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference<List<TotalResult>>() {}); for (TotalResult totalResult : totalResultList) { switch (totalResult.getProvisioningState()) { case "Creating": creatingTotal = totalResult.getCount(); break; case "Succeeded": succeededTotal = totalResult.getCount(); break; case "Updating": updatingTotal = totalResult.getCount(); break; case "Failed": failedTotal = totalResult.getCount(); break; default: otherTotal += totalResult.getCount(); break; } } System.out.println(new StringBuilder() .append("\n\tThe total number of Creating : ").append(creatingTotal) .append("\n\tThe total number of Updating : ").append(updatingTotal) .append("\n\tThe total number of Failed : ").append(failedTotal) .append("\n\tThe total number of Succeeded : ").append(succeededTotal) .append("\n\tThe total number of Other Status : ").append(otherTotal)); if (failedTotal > 0) { break; } else if (succeededTotal < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return succeededTotal.equals(desiredVMCount); }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} private static class TotalResult { private String provisioningState; private Integer count; public String getProvisioningState() { return provisioningState; } public void setProvisioningState(String provisioningState) { this.provisioningState = provisioningState; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } }
In case there are failed VMs (provisionState = Failed) which will cause potential infinite loop, maybe we could add a query for failed instances in the `while` loop and quits if found any? Though it's hard to test the exception behaviour.
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Long desiredVMCount = 6L; final Region region = Region.US_EAST; String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); List<String> vmNameList = new ArrayList<>(); Long total = 0L; Boolean rtnValue = false; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { String vmName = Utils.randomResourceName(azureResourceManager, "javascvm", 15); vmNameList.add("'".concat(vmName).concat("'")); azureResourceManager.virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0." + i + ".0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to batch query the status(the number of provisioningState=Succeeded)."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Succeeded')) ") .append("| project name,id,type,location,subscriptionId,resourceGroup,tags"); while (total < desiredVMCount) { total = resourceGraphManager.resourceProviders() .resources( new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) ) .totalRecords(); if (total < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } rtnValue = true; } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return rtnValue; }
while (total < desiredVMCount) {
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Integer desiredVMCount = 6; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); Integer succeededTotal = 0; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { azureResourceManager.virtualMachines() .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to query the count number for each [provisioningState]."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name contains 'javascvm') ") .append("| extend provisioningState = case(") .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") .append("properties['provisioningState'] =~ 'Accepted','Accepted',") .append("properties['provisioningState'] =~ 'Running','Running',") .append("properties['provisioningState'] =~ 'Ready','Ready',") .append("properties['provisioningState'] =~ 'Creating','Creating',") .append("properties['provisioningState'] =~ 'Created','Created',") .append("properties['provisioningState'] =~ 'Deleting','Deleting',") .append("properties['provisioningState'] =~ 'Deleted','Deleted',") .append("properties['provisioningState'] =~ 'Canceled','Canceled',") .append("properties['provisioningState'] =~ 'Failed','Failed',") .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") .append("properties['provisioningState'] =~ 'Updating','Updating',") .append("properties['provisioningState']) ") .append("| summarize count=count() by provisioningState"); while (succeededTotal < desiredVMCount) { Integer creatingTotal = 0; Integer updatingTotal = 0; Integer failedTotal = 0; Integer otherTotal = 0; succeededTotal = 0; QueryResponse queryResponse = resourceGraphManager.resourceProviders() .resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); List<TotalResult> totalResultList = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference<List<TotalResult>>() {}); for (TotalResult totalResult : totalResultList) { switch (totalResult.getProvisioningState()) { case "Creating": creatingTotal = totalResult.getCount(); break; case "Succeeded": succeededTotal = totalResult.getCount(); break; case "Updating": updatingTotal = totalResult.getCount(); break; case "Failed": failedTotal = totalResult.getCount(); break; default: otherTotal += totalResult.getCount(); break; } } System.out.println(new StringBuilder() .append("\n\tThe total number of Creating : ").append(creatingTotal) .append("\n\tThe total number of Updating : ").append(updatingTotal) .append("\n\tThe total number of Failed : ").append(failedTotal) .append("\n\tThe total number of Succeeded : ").append(succeededTotal) .append("\n\tThe total number of Other Status : ").append(otherTotal)); if (failedTotal > 0) { break; } else if (succeededTotal < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return succeededTotal.equals(desiredVMCount); }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} private static class TotalResult { private String provisioningState; private Integer count; public String getProvisioningState() { return provisioningState; } public void setProvisioningState(String provisioningState) { this.provisioningState = provisioningState; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } }
Agree. May remove the condition of `| where (properties['provisioningState'] =~ ('Succeeded')) `, and calculate via code on how many success, how many in progress, how many failed, print the number out. Break when find failed >0.
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Long desiredVMCount = 6L; final Region region = Region.US_EAST; String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); List<String> vmNameList = new ArrayList<>(); Long total = 0L; Boolean rtnValue = false; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { String vmName = Utils.randomResourceName(azureResourceManager, "javascvm", 15); vmNameList.add("'".concat(vmName).concat("'")); azureResourceManager.virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0." + i + ".0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to batch query the status(the number of provisioningState=Succeeded)."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Succeeded')) ") .append("| project name,id,type,location,subscriptionId,resourceGroup,tags"); while (total < desiredVMCount) { total = resourceGraphManager.resourceProviders() .resources( new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) ) .totalRecords(); if (total < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } rtnValue = true; } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return rtnValue; }
while (total < desiredVMCount) {
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Integer desiredVMCount = 6; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); Integer succeededTotal = 0; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { azureResourceManager.virtualMachines() .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to query the count number for each [provisioningState]."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name contains 'javascvm') ") .append("| extend provisioningState = case(") .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") .append("properties['provisioningState'] =~ 'Accepted','Accepted',") .append("properties['provisioningState'] =~ 'Running','Running',") .append("properties['provisioningState'] =~ 'Ready','Ready',") .append("properties['provisioningState'] =~ 'Creating','Creating',") .append("properties['provisioningState'] =~ 'Created','Created',") .append("properties['provisioningState'] =~ 'Deleting','Deleting',") .append("properties['provisioningState'] =~ 'Deleted','Deleted',") .append("properties['provisioningState'] =~ 'Canceled','Canceled',") .append("properties['provisioningState'] =~ 'Failed','Failed',") .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") .append("properties['provisioningState'] =~ 'Updating','Updating',") .append("properties['provisioningState']) ") .append("| summarize count=count() by provisioningState"); while (succeededTotal < desiredVMCount) { Integer creatingTotal = 0; Integer updatingTotal = 0; Integer failedTotal = 0; Integer otherTotal = 0; succeededTotal = 0; QueryResponse queryResponse = resourceGraphManager.resourceProviders() .resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); List<TotalResult> totalResultList = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference<List<TotalResult>>() {}); for (TotalResult totalResult : totalResultList) { switch (totalResult.getProvisioningState()) { case "Creating": creatingTotal = totalResult.getCount(); break; case "Succeeded": succeededTotal = totalResult.getCount(); break; case "Updating": updatingTotal = totalResult.getCount(); break; case "Failed": failedTotal = totalResult.getCount(); break; default: otherTotal += totalResult.getCount(); break; } } System.out.println(new StringBuilder() .append("\n\tThe total number of Creating : ").append(creatingTotal) .append("\n\tThe total number of Updating : ").append(updatingTotal) .append("\n\tThe total number of Failed : ").append(failedTotal) .append("\n\tThe total number of Succeeded : ").append(succeededTotal) .append("\n\tThe total number of Other Status : ").append(otherTotal)); if (failedTotal > 0) { break; } else if (succeededTotal < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return succeededTotal.equals(desiredVMCount); }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} private static class TotalResult { private String provisioningState; private Integer count; public String getProvisioningState() { return provisioningState; } public void setProvisioningState(String provisioningState) { this.provisioningState = provisioningState; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } }
I am not very happy with 2 queries. Basically you are wasting half of the quota. And this sample is intended to help customer save the quota.
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Long desiredVMCount = 6L; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); List<String> vmNameList = new ArrayList<>(); Long total = 0L; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (long i = 0; i < desiredVMCount; i++) { String vmName = Utils.randomResourceName(azureResourceManager, "javascvm", 15); vmNameList.add("'".concat(vmName).concat("'")); azureResourceManager.virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to batch query the status(the number of provisioningState=Succeeded and Failed)."); StringBuilder succeededQuery = new StringBuilder(); succeededQuery.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Succeeded')) ") .append("| project name,type,properties['provisioningState']"); StringBuilder failedQuery = new StringBuilder(); failedQuery.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Failed')) ") .append("| project name,type,properties['provisioningState']"); while (total < desiredVMCount && resourceGraphManager.resourceProviders().resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(failedQuery.toString())).totalRecords() == 0) { total = resourceGraphManager.resourceProviders().resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(succeededQuery.toString())).totalRecords(); if (total < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return total == desiredVMCount; }
.withQuery(failedQuery.toString())).totalRecords() == 0) {
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Integer desiredVMCount = 6; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); Integer succeededTotal = 0; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { azureResourceManager.virtualMachines() .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to query the count number for each [provisioningState]."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name contains 'javascvm') ") .append("| extend provisioningState = case(") .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") .append("properties['provisioningState'] =~ 'Accepted','Accepted',") .append("properties['provisioningState'] =~ 'Running','Running',") .append("properties['provisioningState'] =~ 'Ready','Ready',") .append("properties['provisioningState'] =~ 'Creating','Creating',") .append("properties['provisioningState'] =~ 'Created','Created',") .append("properties['provisioningState'] =~ 'Deleting','Deleting',") .append("properties['provisioningState'] =~ 'Deleted','Deleted',") .append("properties['provisioningState'] =~ 'Canceled','Canceled',") .append("properties['provisioningState'] =~ 'Failed','Failed',") .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") .append("properties['provisioningState'] =~ 'Updating','Updating',") .append("properties['provisioningState']) ") .append("| summarize count=count() by provisioningState"); while (succeededTotal < desiredVMCount) { Integer creatingTotal = 0; Integer updatingTotal = 0; Integer failedTotal = 0; Integer otherTotal = 0; succeededTotal = 0; QueryResponse queryResponse = resourceGraphManager.resourceProviders() .resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); List<TotalResult> totalResultList = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference<List<TotalResult>>() {}); for (TotalResult totalResult : totalResultList) { switch (totalResult.getProvisioningState()) { case "Creating": creatingTotal = totalResult.getCount(); break; case "Succeeded": succeededTotal = totalResult.getCount(); break; case "Updating": updatingTotal = totalResult.getCount(); break; case "Failed": failedTotal = totalResult.getCount(); break; default: otherTotal += totalResult.getCount(); break; } } System.out.println(new StringBuilder() .append("\n\tThe total number of Creating : ").append(creatingTotal) .append("\n\tThe total number of Updating : ").append(updatingTotal) .append("\n\tThe total number of Failed : ").append(failedTotal) .append("\n\tThe total number of Succeeded : ").append(succeededTotal) .append("\n\tThe total number of Other Status : ").append(otherTotal)); if (failedTotal > 0) { break; } else if (succeededTotal < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return succeededTotal.equals(desiredVMCount); }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() { } }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} private static class TotalResult { private String provisioningState; private Integer count; public String getProvisioningState() { return provisioningState; } public void setProvisioningState(String provisioningState) { this.provisioningState = provisioningState; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } }
Fixed in the new version.
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Long desiredVMCount = 6L; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); List<String> vmNameList = new ArrayList<>(); Long total = 0L; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (long i = 0; i < desiredVMCount; i++) { String vmName = Utils.randomResourceName(azureResourceManager, "javascvm", 15); vmNameList.add("'".concat(vmName).concat("'")); azureResourceManager.virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to batch query the status(the number of provisioningState=Succeeded and Failed)."); StringBuilder succeededQuery = new StringBuilder(); succeededQuery.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Succeeded')) ") .append("| project name,type,properties['provisioningState']"); StringBuilder failedQuery = new StringBuilder(); failedQuery.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Failed')) ") .append("| project name,type,properties['provisioningState']"); while (total < desiredVMCount && resourceGraphManager.resourceProviders().resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(failedQuery.toString())).totalRecords() == 0) { total = resourceGraphManager.resourceProviders().resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(succeededQuery.toString())).totalRecords(); if (total < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return total == desiredVMCount; }
.withQuery(failedQuery.toString())).totalRecords() == 0) {
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Integer desiredVMCount = 6; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); Integer succeededTotal = 0; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { azureResourceManager.virtualMachines() .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to query the count number for each [provisioningState]."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name contains 'javascvm') ") .append("| extend provisioningState = case(") .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") .append("properties['provisioningState'] =~ 'Accepted','Accepted',") .append("properties['provisioningState'] =~ 'Running','Running',") .append("properties['provisioningState'] =~ 'Ready','Ready',") .append("properties['provisioningState'] =~ 'Creating','Creating',") .append("properties['provisioningState'] =~ 'Created','Created',") .append("properties['provisioningState'] =~ 'Deleting','Deleting',") .append("properties['provisioningState'] =~ 'Deleted','Deleted',") .append("properties['provisioningState'] =~ 'Canceled','Canceled',") .append("properties['provisioningState'] =~ 'Failed','Failed',") .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") .append("properties['provisioningState'] =~ 'Updating','Updating',") .append("properties['provisioningState']) ") .append("| summarize count=count() by provisioningState"); while (succeededTotal < desiredVMCount) { Integer creatingTotal = 0; Integer updatingTotal = 0; Integer failedTotal = 0; Integer otherTotal = 0; succeededTotal = 0; QueryResponse queryResponse = resourceGraphManager.resourceProviders() .resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); List<TotalResult> totalResultList = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference<List<TotalResult>>() {}); for (TotalResult totalResult : totalResultList) { switch (totalResult.getProvisioningState()) { case "Creating": creatingTotal = totalResult.getCount(); break; case "Succeeded": succeededTotal = totalResult.getCount(); break; case "Updating": updatingTotal = totalResult.getCount(); break; case "Failed": failedTotal = totalResult.getCount(); break; default: otherTotal += totalResult.getCount(); break; } } System.out.println(new StringBuilder() .append("\n\tThe total number of Creating : ").append(creatingTotal) .append("\n\tThe total number of Updating : ").append(updatingTotal) .append("\n\tThe total number of Failed : ").append(failedTotal) .append("\n\tThe total number of Succeeded : ").append(succeededTotal) .append("\n\tThe total number of Other Status : ").append(otherTotal)); if (failedTotal > 0) { break; } else if (succeededTotal < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return succeededTotal.equals(desiredVMCount); }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() { } }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} private static class TotalResult { private String provisioningState; private Integer count; public String getProvisioningState() { return provisioningState; } public void setProvisioningState(String provisioningState) { this.provisioningState = provisioningState; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } }
Fixed in the new version.
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Long desiredVMCount = 6L; final Region region = Region.US_EAST; String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); List<String> vmNameList = new ArrayList<>(); Long total = 0L; Boolean rtnValue = false; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { String vmName = Utils.randomResourceName(azureResourceManager, "javascvm", 15); vmNameList.add("'".concat(vmName).concat("'")); azureResourceManager.virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0." + i + ".0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to batch query the status(the number of provisioningState=Succeeded)."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name in~ (").append(String.join(",", vmNameList)).append(")) ") .append("| where (properties['provisioningState'] =~ ('Succeeded')) ") .append("| project name,id,type,location,subscriptionId,resourceGroup,tags"); while (total < desiredVMCount) { total = resourceGraphManager.resourceProviders() .resources( new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) ) .totalRecords(); if (total < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } rtnValue = true; } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return rtnValue; }
while (total < desiredVMCount) {
public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { final Integer desiredVMCount = 6; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); final String networkName = Utils.randomResourceName(azureResourceManager, "vnet-", 15); final String subNetName = Utils.randomResourceName(azureResourceManager, "snet-", 15); Integer succeededTotal = 0; try { System.out.println("Creating Resource Group: " + rgName); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/16") .withSubnet(subNetName, "10.0.1.0/24") .create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { azureResourceManager.virtualMachines() .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(primaryNetwork) .withSubnet(subNetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) .withSsh(Utils.sshPublicKey()) .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .beginCreate(); } System.out.println("Use Azure Resource Graph to query the count number for each [provisioningState]."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") .append("| where (name contains 'javascvm') ") .append("| extend provisioningState = case(") .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") .append("properties['provisioningState'] =~ 'Accepted','Accepted',") .append("properties['provisioningState'] =~ 'Running','Running',") .append("properties['provisioningState'] =~ 'Ready','Ready',") .append("properties['provisioningState'] =~ 'Creating','Creating',") .append("properties['provisioningState'] =~ 'Created','Created',") .append("properties['provisioningState'] =~ 'Deleting','Deleting',") .append("properties['provisioningState'] =~ 'Deleted','Deleted',") .append("properties['provisioningState'] =~ 'Canceled','Canceled',") .append("properties['provisioningState'] =~ 'Failed','Failed',") .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") .append("properties['provisioningState'] =~ 'Updating','Updating',") .append("properties['provisioningState']) ") .append("| summarize count=count() by provisioningState"); while (succeededTotal < desiredVMCount) { Integer creatingTotal = 0; Integer updatingTotal = 0; Integer failedTotal = 0; Integer otherTotal = 0; succeededTotal = 0; QueryResponse queryResponse = resourceGraphManager.resourceProviders() .resources(new QueryRequest() .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) .withQuery(queryBuilder.toString()) .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); List<TotalResult> totalResultList = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference<List<TotalResult>>() {}); for (TotalResult totalResult : totalResultList) { switch (totalResult.getProvisioningState()) { case "Creating": creatingTotal = totalResult.getCount(); break; case "Succeeded": succeededTotal = totalResult.getCount(); break; case "Updating": updatingTotal = totalResult.getCount(); break; case "Failed": failedTotal = totalResult.getCount(); break; default: otherTotal += totalResult.getCount(); break; } } System.out.println(new StringBuilder() .append("\n\tThe total number of Creating : ").append(creatingTotal) .append("\n\tThe total number of Updating : ").append(updatingTotal) .append("\n\tThe total number of Failed : ").append(failedTotal) .append("\n\tThe total number of Succeeded : ").append(succeededTotal) .append("\n\tThe total number of Other Status : ").append(otherTotal)); if (failedTotal > 0) { break; } else if (succeededTotal < desiredVMCount) { ResourceManagerUtils.sleep(Duration.ofSeconds(5L)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return succeededTotal.equals(desiredVMCount); }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} }
class CreateMultipleVirtualMachinesAndBatchQueryStatus { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); ResourceGraphManager resourceGraphManager = ResourceGraphManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, resourceGraphManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} private static class TotalResult { private String provisioningState; private Integer count; public String getProvisioningState() { return provisioningState; } public void setProvisioningState(String provisioningState) { this.provisioningState = provisioningState; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } }
Please use checkNotNull precondition function
public ObjectProperty(IJsonNavigatorNode nameNode, IJsonNavigatorNode valueNode) { if (nameNode == null) { throw new IllegalArgumentException("nameNode"); } if (valueNode == null) { throw new IllegalArgumentException("valueNode"); } this.nameNode = nameNode; this.valueNode = valueNode; }
if (nameNode == null) {
public ObjectProperty(IJsonNavigatorNode nameNode, IJsonNavigatorNode valueNode) { checkNotNull(nameNode, "Argument 'nameNode' must not be null."); checkNotNull(valueNode, "Argument 'valueNode' must not be null."); this.nameNode = nameNode; this.valueNode = valueNode; }
class ObjectProperty { /** * Initializes a new instance of the ObjectProperty class. * * @param nameNode The IJsonNavigatorNode to the node that holds the object property name. * @param valueNode The IJsonNavigatorNode to the node that holds the object property value. */ /** * The node that holds the object property name. * * @return The IJsonNavigatorNode that holds the object property name. */ public IJsonNavigatorNode getNameNode() { return nameNode; } /** * The node that holds the object property value. * * @return The IJsonNavigatorNode that holds the object property value. */ public IJsonNavigatorNode getValueNode() { return valueNode; } private final IJsonNavigatorNode nameNode; private final IJsonNavigatorNode valueNode; }
class ObjectProperty { /** * Initializes a new instance of the ObjectProperty class. * * @param nameNode The IJsonNavigatorNode to the node that holds the object property name. * @param valueNode The IJsonNavigatorNode to the node that holds the object property value. */ /** * The node that holds the object property name. * * @return The IJsonNavigatorNode that holds the object property name. */ public IJsonNavigatorNode getNameNode() { return nameNode; } /** * The node that holds the object property value. * * @return The IJsonNavigatorNode that holds the object property value. */ public IJsonNavigatorNode getValueNode() { return valueNode; } private final IJsonNavigatorNode nameNode; private final IJsonNavigatorNode valueNode; }
Updated
public ObjectProperty(IJsonNavigatorNode nameNode, IJsonNavigatorNode valueNode) { if (nameNode == null) { throw new IllegalArgumentException("nameNode"); } if (valueNode == null) { throw new IllegalArgumentException("valueNode"); } this.nameNode = nameNode; this.valueNode = valueNode; }
if (nameNode == null) {
public ObjectProperty(IJsonNavigatorNode nameNode, IJsonNavigatorNode valueNode) { checkNotNull(nameNode, "Argument 'nameNode' must not be null."); checkNotNull(valueNode, "Argument 'valueNode' must not be null."); this.nameNode = nameNode; this.valueNode = valueNode; }
class ObjectProperty { /** * Initializes a new instance of the ObjectProperty class. * * @param nameNode The IJsonNavigatorNode to the node that holds the object property name. * @param valueNode The IJsonNavigatorNode to the node that holds the object property value. */ /** * The node that holds the object property name. * * @return The IJsonNavigatorNode that holds the object property name. */ public IJsonNavigatorNode getNameNode() { return nameNode; } /** * The node that holds the object property value. * * @return The IJsonNavigatorNode that holds the object property value. */ public IJsonNavigatorNode getValueNode() { return valueNode; } private final IJsonNavigatorNode nameNode; private final IJsonNavigatorNode valueNode; }
class ObjectProperty { /** * Initializes a new instance of the ObjectProperty class. * * @param nameNode The IJsonNavigatorNode to the node that holds the object property name. * @param valueNode The IJsonNavigatorNode to the node that holds the object property value. */ /** * The node that holds the object property name. * * @return The IJsonNavigatorNode that holds the object property name. */ public IJsonNavigatorNode getNameNode() { return nameNode; } /** * The node that holds the object property value. * * @return The IJsonNavigatorNode that holds the object property value. */ public IJsonNavigatorNode getValueNode() { return valueNode; } private final IJsonNavigatorNode nameNode; private final IJsonNavigatorNode valueNode; }
```suggestion if (AzureAuthorityHosts.AZURE_PUBLIC_CLOUD.equals(authority)) { ```
static TokenCredential getCredentialByAuthority(String endpoint) { String authority = TestUtils.getAuthority(endpoint); if (authority.equals(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)) { return new DefaultAzureCredentialBuilder() .authorityHost(TestUtils.getAuthority(endpoint)) .build(); } else { return new ClientSecretCredentialBuilder() .tenantId(AZURE_TENANT_ID) .clientId(AZURE_CLIENT_ID) .clientSecret(AZURE_FORM_RECOGNIZER_CLIENT_SECRET) .authorityHost(authority) .build(); } }
if (authority.equals(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)) {
static TokenCredential getCredentialByAuthority(String endpoint) { String authority = TestUtils.getAuthority(endpoint); if (AzureAuthorityHosts.AZURE_PUBLIC_CLOUD.equals(authority)) { return new DefaultAzureCredentialBuilder() .authorityHost(TestUtils.getAuthority(endpoint)) .build(); } else { return new ClientSecretCredentialBuilder() .tenantId(AZURE_TENANT_ID) .clientId(AZURE_CLIENT_ID) .clientSecret(AZURE_FORM_RECOGNIZER_CLIENT_SECRET) .authorityHost(authority) .build(); } }
class DocumentModelAdministrationClientTestBase extends TestProxyTestBase { private static final String BLANK_PDF_PATH = TestUtils.LOCAL_FILE_PATH + TestUtils.BLANK_PDF; Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { durationTestMode = interceptorManager.isPlaybackMode() ? TestUtils.ONE_NANO_DURATION : Constants.DEFAULT_POLL_INTERVAL; } DocumentModelAdministrationClientBuilder getDocumentModelAdminClientBuilder(HttpClient httpClient, DocumentAnalysisServiceVersion serviceVersion, boolean useKeyCredential) { String endpoint = getEndpoint(); DocumentAnalysisAudience audience = TestUtils.getAudience(endpoint); DocumentModelAdministrationClientBuilder builder = new DocumentModelAdministrationClientBuilder() .endpoint(endpoint) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .audience(audience); if (useKeyCredential) { if (interceptorManager.isPlaybackMode()) { builder.credential(new AzureKeyCredential(INVALID_KEY)); setMatchers(); } else if (interceptorManager.isRecordMode()) { builder.credential(new AzureKeyCredential(TestUtils.AZURE_FORM_RECOGNIZER_API_KEY_CONFIGURATION)); builder.addPolicy(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isLiveMode()) { builder.credential(new AzureKeyCredential(TestUtils.AZURE_FORM_RECOGNIZER_API_KEY_CONFIGURATION)); } } else { if (interceptorManager.isPlaybackMode()) { builder.credential(new MockTokenCredential()); setMatchers(); } else if (interceptorManager.isRecordMode()) { builder.credential(getCredentialByAuthority(endpoint)); builder.addPolicy(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isLiveMode()) { builder.credential(getCredentialByAuthority(endpoint)); } } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers(getTestProxySanitizers()); } return builder; } private void setMatchers() { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher())); } static void validateCopyAuthorizationResult(DocumentModelCopyAuthorization actualResult) { assertNotNull(actualResult.getTargetModelId()); assertNotNull(actualResult.getExpiresOn()); assertNotNull(actualResult.getTargetResourceRegion()); assertNotNull(actualResult.getTargetResourceId()); assertNotNull(actualResult.getTargetResourceId()); } static void validateResourceInfo(ResourceDetails actualResourceDetails) { assertNotNull(actualResourceDetails.getCustomDocumentModelLimit()); assertNotNull(actualResourceDetails.getCustomDocumentModelCount()); } void validateDocumentModelData(DocumentModelDetails actualCustomModel) { assertNotNull(actualCustomModel.getCreatedOn()); assertNotNull(actualCustomModel.getModelId()); actualCustomModel.getDocumentTypes().forEach((s, docTypeInfo) -> assertNotNull(docTypeInfo.getFieldSchema())); } void validateClassifierModelData(DocumentClassifierDetails documentClassifierDetails) { assertNotNull(documentClassifierDetails.getCreatedOn()); assertNotNull(documentClassifierDetails.getClassifierId()); assertNotNull(documentClassifierDetails.getServiceVersion()); } void blankPdfDataRunner(BiConsumer<InputStream, Long> testRunner) { final long fileLength = new File(BLANK_PDF_PATH).length(); try { testRunner.accept(new FileInputStream(BLANK_PDF_PATH), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } void buildModelRunner(Consumer<String> testRunner) { TestUtils.getTrainingDataContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } void buildModelErrorRunner(Consumer<String> testRunner) { TestUtils.getErrorTrainingDataContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } void multipageTrainingRunner(Consumer<String> testRunner) { TestUtils.getMultipageTrainingContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } void beginClassifierRunner(Consumer<String> testRunner) { TestUtils.getClassifierTrainingDataContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } void selectionMarkTrainingRunner(Consumer<String> testRunner) { TestUtils.getSelectionMarkTrainingContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } private String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : TestUtils.AZURE_FORM_RECOGNIZER_ENDPOINT_CONFIGURATION; } }
class DocumentModelAdministrationClientTestBase extends TestProxyTestBase { private static final String BLANK_PDF_PATH = TestUtils.LOCAL_FILE_PATH + TestUtils.BLANK_PDF; Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { durationTestMode = interceptorManager.isPlaybackMode() ? TestUtils.ONE_NANO_DURATION : Constants.DEFAULT_POLL_INTERVAL; } DocumentModelAdministrationClientBuilder getDocumentModelAdminClientBuilder(HttpClient httpClient, DocumentAnalysisServiceVersion serviceVersion, boolean useKeyCredential) { String endpoint = getEndpoint(); DocumentAnalysisAudience audience = TestUtils.getAudience(endpoint); DocumentModelAdministrationClientBuilder builder = new DocumentModelAdministrationClientBuilder() .endpoint(endpoint) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .audience(audience); if (useKeyCredential) { if (interceptorManager.isPlaybackMode()) { builder.credential(new AzureKeyCredential(INVALID_KEY)); setMatchers(); } else if (interceptorManager.isRecordMode()) { builder.credential(new AzureKeyCredential(TestUtils.AZURE_FORM_RECOGNIZER_API_KEY_CONFIGURATION)); builder.addPolicy(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isLiveMode()) { builder.credential(new AzureKeyCredential(TestUtils.AZURE_FORM_RECOGNIZER_API_KEY_CONFIGURATION)); } } else { if (interceptorManager.isPlaybackMode()) { builder.credential(new MockTokenCredential()); setMatchers(); } else if (interceptorManager.isRecordMode()) { builder.credential(getCredentialByAuthority(endpoint)); builder.addPolicy(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isLiveMode()) { builder.credential(getCredentialByAuthority(endpoint)); } } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers(getTestProxySanitizers()); } return builder; } private void setMatchers() { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher())); } static void validateCopyAuthorizationResult(DocumentModelCopyAuthorization actualResult) { assertNotNull(actualResult.getTargetModelId()); assertNotNull(actualResult.getExpiresOn()); assertNotNull(actualResult.getTargetResourceRegion()); assertNotNull(actualResult.getTargetResourceId()); assertNotNull(actualResult.getTargetResourceId()); } static void validateResourceInfo(ResourceDetails actualResourceDetails) { assertNotNull(actualResourceDetails.getCustomDocumentModelLimit()); assertNotNull(actualResourceDetails.getCustomDocumentModelCount()); } void validateDocumentModelData(DocumentModelDetails actualCustomModel) { assertNotNull(actualCustomModel.getCreatedOn()); assertNotNull(actualCustomModel.getModelId()); actualCustomModel.getDocumentTypes().forEach((s, docTypeInfo) -> assertNotNull(docTypeInfo.getFieldSchema())); } void validateClassifierModelData(DocumentClassifierDetails documentClassifierDetails) { assertNotNull(documentClassifierDetails.getCreatedOn()); assertNotNull(documentClassifierDetails.getClassifierId()); assertNotNull(documentClassifierDetails.getServiceVersion()); } void blankPdfDataRunner(BiConsumer<InputStream, Long> testRunner) { final long fileLength = new File(BLANK_PDF_PATH).length(); try { testRunner.accept(new FileInputStream(BLANK_PDF_PATH), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } void buildModelRunner(Consumer<String> testRunner) { TestUtils.getTrainingDataContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } void buildModelErrorRunner(Consumer<String> testRunner) { TestUtils.getErrorTrainingDataContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } void multipageTrainingRunner(Consumer<String> testRunner) { TestUtils.getMultipageTrainingContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } void beginClassifierRunner(Consumer<String> testRunner) { TestUtils.getClassifierTrainingDataContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } void selectionMarkTrainingRunner(Consumer<String> testRunner) { TestUtils.getSelectionMarkTrainingContainerHelper(testRunner, interceptorManager.isPlaybackMode()); } private String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : TestUtils.AZURE_FORM_RECOGNIZER_ENDPOINT_CONFIGURATION; } }
Is `prt.resourceType()` always full resource type (include namespace)?
public static String defaultApiVersion(String id, Provider provider) { ResourceId resourceId = ResourceId.fromString(id); String resourceType = resourceId.resourceType().toLowerCase(Locale.ROOT); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceType)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null) { for (ProviderResourceType prt : provider.resourceTypes()) { String fullResourceType = resourceId.fullResourceType().toLowerCase(Locale.ROOT); if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
Double checked, actually no.. The `prt.resourceTypes()` doesn't contain the namespace. It's the response from the WebApp client API that does, `Microsoft.Web/sites/config`. I wasn't able to find whether it ever will from their api docs: https://learn.microsoft.com/en-us/rest/api/resources/provider-resource-types/list?tabs=HTTP#providerresourcetypelistresult . But I assume they won't since their examples don't: https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/resource-providers-and-types I'll change the implementation to compare the exact resource type without namespace. And `prt.resourceTypes()` for `Microsoft.Web` doesn't contain `sites/confg` either, which always makes the test case use the default api-version.. I'll delete the test for this one.
public static String defaultApiVersion(String id, Provider provider) { ResourceId resourceId = ResourceId.fromString(id); String resourceType = resourceId.resourceType().toLowerCase(Locale.ROOT); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceType)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null) { for (ProviderResourceType prt : provider.resourceTypes()) { String fullResourceType = resourceId.fullResourceType().toLowerCase(Locale.ROOT); if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
Wondering whether we should make 2 pass. 1st to check for exact match of 2 resourceType (include parents). If 1st pass not found, do a 2nd pass with relaxed condition (current condition).
public static String defaultApiVersion(String id, Provider provider) { ResourceId resourceId = ResourceId.fromString(id); String resourceType = resourceId.resourceType().toLowerCase(Locale.ROOT); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceType)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null) { for (ProviderResourceType prt : provider.resourceTypes()) { String fullResourceType = resourceId.fullResourceType().toLowerCase(Locale.ROOT); if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
By `current condition` you mean the full resource type including namespace right? Sounds good to me.
public static String defaultApiVersion(String id, Provider provider) { ResourceId resourceId = ResourceId.fromString(id); String resourceType = resourceId.resourceType().toLowerCase(Locale.ROOT); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceType)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null) { for (ProviderResourceType prt : provider.resourceTypes()) { String fullResourceType = resourceId.fullResourceType().toLowerCase(Locale.ROOT); if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
By "current condition" I mean your current `endsWith` (or maybe "previous condition" of `contains`?). Point is a relaxed match that might work.
public static String defaultApiVersion(String id, Provider provider) { ResourceId resourceId = ResourceId.fromString(id); String resourceType = resourceId.resourceType().toLowerCase(Locale.ROOT); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceType)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null) { for (ProviderResourceType prt : provider.resourceTypes()) { String fullResourceType = resourceId.fullResourceType().toLowerCase(Locale.ROOT); if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
updated
public static String defaultApiVersion(String id, Provider provider) { ResourceId resourceId = ResourceId.fromString(id); String resourceType = resourceId.resourceType().toLowerCase(Locale.ROOT); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceType)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null) { for (ProviderResourceType prt : provider.resourceTypes()) { String fullResourceType = resourceId.fullResourceType().toLowerCase(Locale.ROOT); if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.endsWith(prt.resourceType().toLowerCase(Locale.ROOT))) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
Does it mean we currently only do exact match? If exact match not found, fallback is on its parent via `defaultApiVersion(parent.id(), provider)`?
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); String fullResourceType = resourceId.fullResourceType(); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace) || fullResourceType.contains(prt.resourceType())) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
updated to do exact match first, then relaxed match
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); String fullResourceType = resourceId.fullResourceType(); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace) || fullResourceType.contains(prt.resourceType())) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
This match logic (type from resource contains type from prt) seems the opposite of previous logic (type from prt contains type from resource, maybe not the full type)? Though it does handle the case that namespace get included in type from prt (but does it exist?).
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } String fullResourceType = resourceId.fullResourceType(); for (ProviderResourceType prt : provider.resourceTypes()) { if (fullResourceType.contains(prt.resourceType())) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.contains(prt.resourceType())) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
Yeah, it's the opposite. Yet `prt.resourceType()` maybe not the full type? Wondering what the behaviour is. I'm still trying to figure out the relax match situation, is it like: full resource type -> `level1/level2/level3/level4` prt.resourceType() -> `level1/level4` or only `level4` ? in which case the original relaxed match makes sense to me.
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } String fullResourceType = resourceId.fullResourceType(); for (ProviderResourceType prt : provider.resourceTypes()) { if (fullResourceType.contains(prt.resourceType())) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.contains(prt.resourceType())) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
You can take a look on the list of prt. `level1/level4` seems not make sense. But I am not sure if `level4` could happen (hope not, it is inherently ambiguous). You can also check with .NET. I assume they have similar logic (they may also have a cache :-) ) BTW, you need consistent `.toLowerCase(Locale.ROOT)` here.
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } String fullResourceType = resourceId.fullResourceType(); for (ProviderResourceType prt : provider.resourceTypes()) { if (fullResourceType.contains(prt.resourceType())) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.contains(prt.resourceType())) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
Though I am still a bit unsure about relax match condition `fullResourceType.contains(prt.resourceType())`. It seems already covers the "parent" fallback, (I assume if parent id has exact match, here the relax match would already matches it?) https://github.com/Azure/azure-sdk-for-java/blob/9c354f639a9b260e8461c8f17e6b8602a5b43e70/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/ResourceUtils.java#L183 But it may find a less correct "parent" e.g. `level1/level2/level3/level4` may match `level1` first, before its chance of match `level1/level2/level3` Or it may just match to `level2`?
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } String fullResourceType = resourceId.fullResourceType(); for (ProviderResourceType prt : provider.resourceTypes()) { if (fullResourceType.contains(prt.resourceType())) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.contains(prt.resourceType())) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
Any better idea? May be "exact match" first, "parent match" second, then the last chance "relax match"?
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } String fullResourceType = resourceId.fullResourceType(); for (ProviderResourceType prt : provider.resourceTypes()) { if (fullResourceType.contains(prt.resourceType())) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.contains(prt.resourceType())) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
Offline discussion: remove the `relax match` first, deal with it when needed.
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } String fullResourceType = resourceId.fullResourceType(); for (ProviderResourceType prt : provider.resourceTypes()) { if (fullResourceType.contains(prt.resourceType())) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
if (fullResourceType.contains(prt.resourceType())) {
public static String defaultApiVersion(String id, Provider provider) { if (id == null || provider == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); String resourceTypeWithoutNamespace = getFullResourceTypeWithoutNamespace(resourceId); for (ProviderResourceType prt : provider.resourceTypes()) { if (prt.resourceType().equalsIgnoreCase(resourceTypeWithoutNamespace)) { return prt.defaultApiVersion() == null ? prt.apiVersions().get(0) : prt.defaultApiVersion(); } } ResourceId parent = resourceId.parent(); if (parent != null && !CoreUtils.isNullOrEmpty(parent.id())) { return defaultApiVersion(parent.id(), provider); } else { return provider.resourceTypes().get(0).apiVersions().get(0); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
class ResourceUtils { private ResourceUtils() { } /** * Extract resource group from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; } /** * Extract the subscription ID from a resource ID string. * * @param id the resource ID string * @return the subscription ID */ public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; } /** * Extract resource provider from a resource ID string. * * @param id the resource ID string * @return the resource group name */ public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; } /** * Extract resource type from a resource ID string. * * @param id the resource ID string * @return the resource type */ public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; } /** * Extract parent resource ID from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return * subscriptions/s/resourcegroups/r/foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentResourceIdFromResourceId(String id) { if (id == null) { return null; } ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() != null) { return ResourceId.fromString(id).parent().id(); } return null; } /** * Extract parent resource path from a resource ID string. * E.g. subscriptions/s/resourcegroups/r/foos/foo/bars/bar will return foos/foo. * * @param id the resource ID string * @return the parent resource ID */ public static String parentRelativePathFromResourceId(String id) { if (id == null) { return null; } ResourceId parent = ResourceId.fromString(id).parent(); if (parent != null) { return parent.resourceType() + "/" + parent.name(); } return ""; } /** * Extract the relative path to the current resource provider. * E.g. subscriptions/sub1/resourceGroups/rg1/providers/Microsoft.Foo/foos/foo1 will return foos/foo1. * * @param id the id of the resource * @return the relative path */ public static String relativePathFromResourceId(String id) { if (id == null) { return null; } String[] paths = id.split("/providers/" + resourceProviderFromResourceId(id) + "/", 2); if (paths.length == 1) { return ""; } else { return paths[1]; } } /** * Extract information from a resource ID string with the resource type * as the identifier. * * @param id the resource ID * @param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts" * @return the information extracted from the identifier */ public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } } /** * Extract name of the resource from a resource ID. * * @param id the resource ID * @return the name of the resource */ public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; } /** * Find out the default api version to make a REST request with from * the resource provider. * * @param id the resource ID * @param provider the resource provider * @return the default api version to use */ /** * Creates a resource ID from information of a generic resource. * * @param subscriptionId the subscription UUID * @param resourceGroupName the resource group name * @param resourceProviderNamespace the resource provider namespace * @param resourceType the type of the resource or nested resource * @param resourceName name of the resource or nested resource * @param parentResourcePath parent resource's relative path to the provider, * if the resource is a generic resource * @return the resource ID string */ public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** * Ensure that the resource ID is properly encoded for path parameter. * * @param resourceId the resource ID, whether url-encoded or not * @return properly encoded resource ID */ public static String encodeResourceId(String resourceId) { if (resourceId == null) { return null; } return resourceId.replaceAll(" ", "%20"); } private static String getFullResourceTypeWithoutNamespace(ResourceId resourceId) { return resourceId.fullResourceType() .substring(resourceId.fullResourceType().indexOf("/") + 1) .toLowerCase(Locale.ROOT); } }
Old test case does not make much sense to me. Why remove a good backend, while replace it with a bad one? Hence I only leave the old logic in `InternetMinimal` case, as a test on clean-up logic of the removed backend. The other 2 cases change to this (without `withoutBackend`).
public LoadBalancer updateResource(LoadBalancer resource) throws Exception { LoadBalancerBackend backend = resource.backends().values().iterator().next(); Assertions.assertNotNull(backend); LoadBalancingRule lbRule = resource.loadBalancingRules().get("lbrule1"); Assertions.assertNotNull(lbRule); resource = resource .update() .updatePrivateFrontend(lbRule.frontend().name()) .withExistingSubnet(this.network, "subnet2") .withPrivateIpAddressStatic("10.0.0.13") .parent() .defineTcpProbe("tcpprobe") .withPort(22) .attach() .defineHttpProbe("httpprobe") .withRequestPath("/foo") .withNumberOfProbes(3) .withPort(443) .attach() .updateLoadBalancingRule("lbrule1") .toBackendPort(8080) .withIdleTimeoutInMinutes(11) .withProbe("tcpprobe") .parent() .defineLoadBalancingRule("lbrule2") .withProtocol(TransportProtocol.UDP) .fromFrontend(lbRule.frontend().name()) .fromFrontendPort(22) .toBackend(backend.name()) .withProbe("httpprobe") .attach() .withTag("tag1", "value1") .withTag("tag2", "value2") .apply(); Assertions.assertTrue(resource.tags().containsKey("tag1")); Assertions.assertEquals(1, resource.frontends().size()); Assertions.assertEquals(1, resource.privateFrontends().size()); Assertions.assertEquals(0, resource.publicFrontends().size()); LoadBalancerFrontend frontend = resource.frontends().get(lbRule.frontend().name()); Assertions.assertNotNull(frontend); Assertions.assertFalse(frontend.isPublic()); LoadBalancerPrivateFrontend privateFrontend = (LoadBalancerPrivateFrontend) frontend; Assertions.assertTrue("subnet2".equalsIgnoreCase(privateFrontend.subnetName())); Assertions.assertEquals(IpAllocationMethod.STATIC, privateFrontend.privateIpAllocationMethod()); Assertions.assertTrue("10.0.0.13".equalsIgnoreCase(privateFrontend.privateIpAddress())); Assertions.assertEquals(2, privateFrontend.loadBalancingRules().size()); Assertions.assertEquals(1, resource.tcpProbes().size()); LoadBalancerTcpProbe tcpProbe = resource.tcpProbes().get("tcpprobe"); Assertions.assertNotNull(tcpProbe); Assertions.assertEquals(22, tcpProbe.port()); Assertions.assertTrue(tcpProbe.loadBalancingRules().containsKey("lbrule1")); LoadBalancerHttpProbe httpProbe = resource.httpProbes().get("httpprobe"); Assertions.assertNotNull(httpProbe); Assertions.assertEquals(3, httpProbe.numberOfProbes()); Assertions.assertTrue("/foo".equalsIgnoreCase(httpProbe.requestPath())); Assertions.assertTrue(httpProbe.loadBalancingRules().containsKey("lbrule2")); Assertions.assertEquals(1, resource.backends().size()); Assertions.assertTrue(resource.backends().containsKey(backend.name())); lbRule = resource.loadBalancingRules().get("lbrule1"); Assertions.assertNotNull(lbRule); Assertions.assertEquals(8080, lbRule.backendPort()); Assertions.assertNotNull(lbRule.frontend()); Assertions.assertEquals(11, lbRule.idleTimeoutInMinutes()); Assertions.assertNotNull(lbRule.probe()); Assertions.assertEquals(tcpProbe.name(), lbRule.probe().name()); Assertions.assertNotNull(lbRule.backend()); Assertions.assertTrue(backend.name().equalsIgnoreCase(lbRule.backend().name())); lbRule = resource.loadBalancingRules().get("lbrule2"); Assertions.assertNotNull(lbRule); Assertions.assertEquals(22, lbRule.frontendPort()); Assertions.assertNotNull(lbRule.frontend()); Assertions.assertTrue("httpprobe".equalsIgnoreCase(lbRule.probe().name())); Assertions.assertEquals(TransportProtocol.UDP, lbRule.protocol()); Assertions.assertNotNull(lbRule.backend()); Assertions.assertTrue(backend.name().equalsIgnoreCase(lbRule.backend().name())); return resource; }
.withIdleTimeoutInMinutes(11)
public LoadBalancer updateResource(LoadBalancer resource) throws Exception { resource = resource .update() .withoutBackend("backend1") .withoutLoadBalancingRule("rule1") .withoutInboundNatPool("natpool1") .withoutProbe("httpProbe1") .withoutProbe("tcpProbe1") .withTag("tag1", "value1") .withTag("tag2", "value2") .apply(); resource.refresh(); Assertions.assertTrue(resource.tags().containsKey("tag1")); Assertions.assertEquals(1, resource.frontends().size()); Assertions.assertEquals(1, resource.publicFrontends().size()); Assertions.assertEquals(0, resource.privateFrontends().size()); Assertions.assertFalse(resource.httpProbes().containsKey("httpProbe1")); Assertions.assertFalse(resource.httpProbes().containsKey("tcpProbe1")); Assertions.assertEquals(0, resource.httpProbes().size()); Assertions.assertEquals(0, resource.tcpProbes().size()); Assertions.assertEquals(0, resource.backends().size()); Assertions.assertFalse(resource.loadBalancingRules().containsKey("rule1")); Assertions.assertEquals(0, resource.loadBalancingRules().size()); Assertions.assertFalse(resource.inboundNatPools().containsKey("natpool1")); return resource; }
class InternetWithNatPool extends TestTemplate<LoadBalancer, LoadBalancers> { private final ComputeManager computeManager; /** * Test of a load balancer with a NAT pool. * * @param computeManager compute manager */ public InternetWithNatPool(ComputeManager computeManager) { initializeResourceNames(computeManager.resourceManager().internalContext()); this.computeManager = computeManager; } @Override public void print(LoadBalancer resource) { printLB(resource); } @Override public LoadBalancer createResource(LoadBalancers resources) throws Exception { VirtualMachine[] existingVMs = ensureVMs(resources.manager().networks(), this.computeManager, 2); ensurePIPs(resources.manager().publicIpAddresses()); PublicIpAddress pip0 = resources.manager().publicIpAddresses().getByResourceGroup(groupName, pipNames[0]); LoadBalancer lb = resources .define(lbName) .withRegion(region) .withExistingResourceGroup(groupName) .defineLoadBalancingRule("rule1") .withProtocol(TransportProtocol.TCP) .fromExistingPublicIPAddress(pip0) .fromFrontendPort(81) .toBackend("backend1") .toBackendPort(82) .withProbe("tcpProbe1") .withIdleTimeoutInMinutes(10) .withLoadDistribution(LoadDistribution.SOURCE_IP) .attach() .defineInboundNatPool("natpool1") .withProtocol(TransportProtocol.TCP) .fromExistingPublicIPAddress(pip0) .fromFrontendPortRange(2000, 2001) .toBackendPort(8080) .attach() .defineTcpProbe("tcpProbe1") .withPort(25) .withIntervalInSeconds(15) .withNumberOfProbes(5) .attach() .defineHttpProbe("httpProbe1") .withRequestPath("/") .withIntervalInSeconds(13) .withNumberOfProbes(4) .attach() .defineBackend("backend1") .withExistingVirtualMachines(existingVMs) .attach() .create(); Assertions.assertEquals(1, lb.frontends().size()); Assertions.assertEquals(1, lb.publicFrontends().size()); Assertions.assertEquals(0, lb.privateFrontends().size()); LoadBalancerFrontend frontend = lb.frontends().values().iterator().next(); Assertions.assertTrue(frontend.isPublic()); LoadBalancerPublicFrontend publicFrontend = (LoadBalancerPublicFrontend) frontend; Assertions.assertTrue(pip0.id().equalsIgnoreCase(publicFrontend.publicIpAddressId())); Assertions.assertEquals(1, lb.backends().size()); Assertions.assertEquals(1, lb.httpProbes().size()); Assertions.assertTrue(lb.httpProbes().containsKey("httpProbe1")); Assertions.assertEquals(1, lb.tcpProbes().size()); Assertions.assertTrue(lb.tcpProbes().containsKey("tcpProbe1")); Assertions.assertEquals(1, lb.loadBalancingRules().size()); Assertions.assertTrue(lb.loadBalancingRules().containsKey("rule1")); LoadBalancingRule rule = lb.loadBalancingRules().get("rule1"); Assertions.assertNotNull(rule.backend()); Assertions.assertTrue(rule.probe().name().equalsIgnoreCase("tcpProbe1")); Assertions.assertTrue(lb.inboundNatPools().containsKey("natpool1")); Assertions.assertEquals(1, lb.inboundNatPools().size()); LoadBalancerInboundNatPool inboundNatPool = lb.inboundNatPools().get("natpool1"); Assertions.assertEquals(2000, inboundNatPool.frontendPortRangeStart()); Assertions.assertEquals(2001, inboundNatPool.frontendPortRangeEnd()); Assertions.assertEquals(8080, inboundNatPool.backendPort()); return lb; } @Override }
class InternetWithNatPool extends TestTemplate<LoadBalancer, LoadBalancers> { private final ComputeManager computeManager; /** * Test of a load balancer with a NAT pool. * * @param computeManager compute manager */ public InternetWithNatPool(ComputeManager computeManager) { initializeResourceNames(computeManager.resourceManager().internalContext()); this.computeManager = computeManager; } @Override public void print(LoadBalancer resource) { printLB(resource); } @Override public LoadBalancer createResource(LoadBalancers resources) throws Exception { VirtualMachine[] existingVMs = ensureVMs(resources.manager().networks(), this.computeManager, 2); ensurePIPs(resources.manager().publicIpAddresses()); PublicIpAddress pip0 = resources.manager().publicIpAddresses().getByResourceGroup(groupName, pipNames[0]); LoadBalancer lb = resources .define(lbName) .withRegion(region) .withExistingResourceGroup(groupName) .defineLoadBalancingRule("rule1") .withProtocol(TransportProtocol.TCP) .fromExistingPublicIPAddress(pip0) .fromFrontendPort(81) .toBackend("backend1") .toBackendPort(82) .withProbe("tcpProbe1") .withIdleTimeoutInMinutes(10) .withLoadDistribution(LoadDistribution.SOURCE_IP) .attach() .defineInboundNatPool("natpool1") .withProtocol(TransportProtocol.TCP) .fromExistingPublicIPAddress(pip0) .fromFrontendPortRange(2000, 2001) .toBackendPort(8080) .attach() .defineTcpProbe("tcpProbe1") .withPort(25) .withIntervalInSeconds(15) .withNumberOfProbes(5) .attach() .defineHttpProbe("httpProbe1") .withRequestPath("/") .withIntervalInSeconds(13) .withNumberOfProbes(4) .attach() .defineBackend("backend1") .withExistingVirtualMachines(existingVMs) .attach() .create(); Assertions.assertEquals(1, lb.frontends().size()); Assertions.assertEquals(1, lb.publicFrontends().size()); Assertions.assertEquals(0, lb.privateFrontends().size()); LoadBalancerFrontend frontend = lb.frontends().values().iterator().next(); Assertions.assertTrue(frontend.isPublic()); LoadBalancerPublicFrontend publicFrontend = (LoadBalancerPublicFrontend) frontend; Assertions.assertTrue(pip0.id().equalsIgnoreCase(publicFrontend.publicIpAddressId())); Assertions.assertEquals(1, lb.backends().size()); Assertions.assertEquals(1, lb.httpProbes().size()); Assertions.assertTrue(lb.httpProbes().containsKey("httpProbe1")); Assertions.assertEquals(1, lb.tcpProbes().size()); Assertions.assertTrue(lb.tcpProbes().containsKey("tcpProbe1")); Assertions.assertEquals(1, lb.loadBalancingRules().size()); Assertions.assertTrue(lb.loadBalancingRules().containsKey("rule1")); LoadBalancingRule rule = lb.loadBalancingRules().get("rule1"); Assertions.assertNotNull(rule.backend()); Assertions.assertTrue(rule.probe().name().equalsIgnoreCase("tcpProbe1")); Assertions.assertTrue(lb.inboundNatPools().containsKey("natpool1")); Assertions.assertEquals(1, lb.inboundNatPools().size()); LoadBalancerInboundNatPool inboundNatPool = lb.inboundNatPools().get("natpool1"); Assertions.assertEquals(2000, inboundNatPool.frontendPortRangeStart()); Assertions.assertEquals(2001, inboundNatPool.frontendPortRangeEnd()); Assertions.assertEquals(8080, inboundNatPool.backendPort()); return lb; } @Override }
Trying to learn the propagation logic: Is it the case that, if the processor-instrumentation is ON, the endSpan call happens further downstream in the ServiceBusProcessorClient?
protected void hookOnNext(ServiceBusMessageContext message) { Context span = instrumentation.instrumentProcess("ServiceBus.process", message.getMessage(), Context.NONE); AutoCloseable scope = tracer.makeSpanCurrent(span); try { downstream.onNext(message); if (!instrumentation.isProcessorInstrumentation()) { tracer.endSpan(null, span, scope); } } catch (Throwable t) { tracer.endSpan(t, span, scope); throw t; } }
tracer.endSpan(null, span, scope);
protected void hookOnNext(ServiceBusMessageContext message) { Context span = instrumentation.instrumentProcess("ServiceBus.process", message.getMessage(), Context.NONE); message.getMessage().setContext(span); AutoCloseable scope = tracer.makeSpanCurrent(span); try { downstream.onNext(message); if (!instrumentation.isProcessorInstrumentation()) { tracer.endSpan(null, span, scope); } } catch (Throwable t) { tracer.endSpan(t, span, scope); throw t; } }
class TracingSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private final CoreSubscriber<? super ServiceBusMessageContext> downstream; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; TracingSubscriber(CoreSubscriber<? super ServiceBusMessageContext> downstream, ServiceBusReceiverInstrumentation instrumentation) { this.downstream = downstream; this.instrumentation = instrumentation; this.tracer = instrumentation.getTracer(); } @Override public reactor.util.context.Context currentContext() { return downstream.currentContext(); } @Override protected void hookOnSubscribe(Subscription subscription) { downstream.onSubscribe(this); } @Override @Override protected void hookOnError(Throwable throwable) { downstream.onError(throwable); } @Override protected void hookOnComplete() { downstream.onComplete(); } }
class TracingSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private final CoreSubscriber<? super ServiceBusMessageContext> downstream; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; TracingSubscriber(CoreSubscriber<? super ServiceBusMessageContext> downstream, ServiceBusReceiverInstrumentation instrumentation) { this.downstream = downstream; this.instrumentation = instrumentation; this.tracer = instrumentation.getTracer(); } @Override public reactor.util.context.Context currentContext() { return downstream.currentContext(); } @Override protected void hookOnSubscribe(Subscription subscription) { downstream.onSubscribe(this); } @Override @Override protected void hookOnError(Throwable throwable) { downstream.onError(throwable); } @Override protected void hookOnComplete() { downstream.onComplete(); } }
yes, flux trace here is the first to be invoked after message is received and when it's dispatched to the app - we track metrics and start span there for async receiver and processor (sync receiver is a different beast). In case of async client, we have limited control over subscriber behavior and don't know if it's sync or async - the best we can do is to end span here once downstream subscriber `onNext` completes. In the case of processor, we use parallel flux there and the downstream subscriber completes before the processing callback starts. So instead of ending the span here, we keep it in the context attached to the message (it was well-hidden - I made it a bit more straightforward). In the processor, we'll get this span from message and end it there. The order of things in case of consurrent processing is the following: 1. message is received and is being dispatched to the user's subscriber 2. FluxTrace starts processing span and attaches it to the message's context 3. downstream subscribers do their stuff (lock renewal, messages are added to internal queue for parallel scheduling) 4. `downstream.onNext(message)` completes 5. process callback on processor is called 6. once it's over, we get span from the message context and end it I hope to find a nicer/easier way to plug tracing in the v2 stack.
protected void hookOnNext(ServiceBusMessageContext message) { Context span = instrumentation.instrumentProcess("ServiceBus.process", message.getMessage(), Context.NONE); AutoCloseable scope = tracer.makeSpanCurrent(span); try { downstream.onNext(message); if (!instrumentation.isProcessorInstrumentation()) { tracer.endSpan(null, span, scope); } } catch (Throwable t) { tracer.endSpan(t, span, scope); throw t; } }
tracer.endSpan(null, span, scope);
protected void hookOnNext(ServiceBusMessageContext message) { Context span = instrumentation.instrumentProcess("ServiceBus.process", message.getMessage(), Context.NONE); message.getMessage().setContext(span); AutoCloseable scope = tracer.makeSpanCurrent(span); try { downstream.onNext(message); if (!instrumentation.isProcessorInstrumentation()) { tracer.endSpan(null, span, scope); } } catch (Throwable t) { tracer.endSpan(t, span, scope); throw t; } }
class TracingSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private final CoreSubscriber<? super ServiceBusMessageContext> downstream; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; TracingSubscriber(CoreSubscriber<? super ServiceBusMessageContext> downstream, ServiceBusReceiverInstrumentation instrumentation) { this.downstream = downstream; this.instrumentation = instrumentation; this.tracer = instrumentation.getTracer(); } @Override public reactor.util.context.Context currentContext() { return downstream.currentContext(); } @Override protected void hookOnSubscribe(Subscription subscription) { downstream.onSubscribe(this); } @Override @Override protected void hookOnError(Throwable throwable) { downstream.onError(throwable); } @Override protected void hookOnComplete() { downstream.onComplete(); } }
class TracingSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private final CoreSubscriber<? super ServiceBusMessageContext> downstream; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; TracingSubscriber(CoreSubscriber<? super ServiceBusMessageContext> downstream, ServiceBusReceiverInstrumentation instrumentation) { this.downstream = downstream; this.instrumentation = instrumentation; this.tracer = instrumentation.getTracer(); } @Override public reactor.util.context.Context currentContext() { return downstream.currentContext(); } @Override protected void hookOnSubscribe(Subscription subscription) { downstream.onSubscribe(this); } @Override @Override protected void hookOnError(Throwable throwable) { downstream.onError(throwable); } @Override protected void hookOnComplete() { downstream.onComplete(); } }
Thank you for the clear and detailed explanation! Yes, this is easy to plug into v2 stack. Once this improvement is merged, I will try to replicate this in V2 and request your feedback.
protected void hookOnNext(ServiceBusMessageContext message) { Context span = instrumentation.instrumentProcess("ServiceBus.process", message.getMessage(), Context.NONE); AutoCloseable scope = tracer.makeSpanCurrent(span); try { downstream.onNext(message); if (!instrumentation.isProcessorInstrumentation()) { tracer.endSpan(null, span, scope); } } catch (Throwable t) { tracer.endSpan(t, span, scope); throw t; } }
tracer.endSpan(null, span, scope);
protected void hookOnNext(ServiceBusMessageContext message) { Context span = instrumentation.instrumentProcess("ServiceBus.process", message.getMessage(), Context.NONE); message.getMessage().setContext(span); AutoCloseable scope = tracer.makeSpanCurrent(span); try { downstream.onNext(message); if (!instrumentation.isProcessorInstrumentation()) { tracer.endSpan(null, span, scope); } } catch (Throwable t) { tracer.endSpan(t, span, scope); throw t; } }
class TracingSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private final CoreSubscriber<? super ServiceBusMessageContext> downstream; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; TracingSubscriber(CoreSubscriber<? super ServiceBusMessageContext> downstream, ServiceBusReceiverInstrumentation instrumentation) { this.downstream = downstream; this.instrumentation = instrumentation; this.tracer = instrumentation.getTracer(); } @Override public reactor.util.context.Context currentContext() { return downstream.currentContext(); } @Override protected void hookOnSubscribe(Subscription subscription) { downstream.onSubscribe(this); } @Override @Override protected void hookOnError(Throwable throwable) { downstream.onError(throwable); } @Override protected void hookOnComplete() { downstream.onComplete(); } }
class TracingSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private final CoreSubscriber<? super ServiceBusMessageContext> downstream; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; TracingSubscriber(CoreSubscriber<? super ServiceBusMessageContext> downstream, ServiceBusReceiverInstrumentation instrumentation) { this.downstream = downstream; this.instrumentation = instrumentation; this.tracer = instrumentation.getTracer(); } @Override public reactor.util.context.Context currentContext() { return downstream.currentContext(); } @Override protected void hookOnSubscribe(Subscription subscription) { downstream.onSubscribe(this); } @Override @Override protected void hookOnError(Throwable throwable) { downstream.onError(throwable); } @Override protected void hookOnComplete() { downstream.onComplete(); } }
Worth adding this comment as what we have on the transitTimeout validation: // Transit timeout can be a normal symptom under high CPU load. 
// When request timeout due to high CPU,
 // close the existing the connection and re-establish a new one will not help the issue but rather make it worse, return fast
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency > this.nonRespondingChannelReadDelayTimeLimitInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) {
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency >= this.nonRespondingChannelReadDelayTimeLimitInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
```suggestion if (readSuccessRecency >= this.nonRespondingChannelReadDelayTimeLimitInNanos) { ```
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency > this.nonRespondingChannelReadDelayTimeLimitInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
if (readSuccessRecency > this.nonRespondingChannelReadDelayTimeLimitInNanos) {
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency >= this.nonRespondingChannelReadDelayTimeLimitInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
Fixed in next iteration.
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency > this.nonRespondingChannelReadDelayTimeLimitInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) {
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency >= this.nonRespondingChannelReadDelayTimeLimitInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
Fixed in next iteration.
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency > this.nonRespondingChannelReadDelayTimeLimitInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
if (readSuccessRecency > this.nonRespondingChannelReadDelayTimeLimitInNanos) {
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency >= this.nonRespondingChannelReadDelayTimeLimitInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
I removed RetryPolicy since we have our own built-in local storage retry policy, and so this could be confusing (and unnecessary)
public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; }
this.httpLogOptions = httpLogOptions;
public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions httpLogOptions) { if (frozen) { throw LOGGER.logExceptionAsError(new IllegalStateException( "httpLogOptions cannot be changed after any of the build methods have been called")); } this.httpLogOptions = httpLogOptions; return this; }
class AzureMonitorExporterBuilder { private ConnectionString connectionString; private TokenCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); private ClientOptions clientOptions; private HttpPipeline httpPipeline; private AzureMonitorExporterServiceVersion serviceVersion; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { } /** * Sets the HTTP pipeline to use for the service client. If {@code httpPipeline} is set, all other * settings are ignored. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving * responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param httpClient The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param httpLogOptions The logging configuration to use when sending and receiving HTTP * requests/responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param httpPipelinePolicy a policy to be added to the http pipeline. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addHttpPipelinePolicy(HttpPipelinePolicy httpPipelinePolicy) { httpPipelinePolicies.add( Objects.requireNonNull(httpPipelinePolicy, "'policy' cannot be null.")); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ public AzureMonitorExporterBuilder connectionString(String connectionString) { this.connectionString = ConnectionString.parse(connectionString); return this; } /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion( AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } /** * Configures an {@link AutoConfiguredOpenTelemetrySdkBuilder} based on the options set in the builder. */ public void build(AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder) { validate(); LazyConnectionString lazyConnectionString = new LazyConnectionString(connectionString); LazyTelemetryItemExporter lazyTelemetryItemExporter = new LazyTelemetryItemExporter(); LazyHttpPipeline lazyHttpPipeline = new LazyHttpPipeline(credential, httpClient, httpLogOptions, httpPipelinePolicies, clientOptions, httpPipeline); AzureMonitorExporterBuilderHelper helper = new AzureMonitorExporterBuilderHelper(serviceVersion, lazyConnectionString, lazyTelemetryItemExporter, lazyHttpPipeline); helper.build(sdkBuilder); } private void validate() { if (httpPipeline != null) { if (credential != null) { throw new IllegalStateException("'credential' is not supported when custom 'httpPipeline' is specified"); } if (httpClient != null) { throw new IllegalStateException("'httpClient' is not supported when custom 'httpPipeline' is specified"); } if (httpLogOptions != null) { throw new IllegalStateException("'httpLogOptions' is not supported when custom 'httpPipeline' is specified"); } if (!httpPipelinePolicies.isEmpty()) { throw new IllegalStateException("'httpPipelinePolicies' is not supported when custom 'httpPipeline' is specified"); } if (clientOptions != null) { throw new IllegalStateException("'clientOptions' is not supported when custom 'httpPipeline' is specified"); } } } }
class AzureMonitorExporterBuilder { private static final ClientLogger LOGGER = new ClientLogger(AzureMonitorExporterBuilder.class); private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-monitor-opentelemetry-exporter.properties"); private ConnectionString connectionString; private TokenCredential credential; @SuppressWarnings({"UnusedVariable", "FieldCanBeLocal"}) private AzureMonitorExporterServiceVersion serviceVersion; private HttpPipeline httpPipeline; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); private ClientOptions clientOptions; private boolean frozen; private HttpPipeline builtHttpPipeline; private TelemetryItemExporter builtTelemetryItemExporter; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { } /** * Sets the HTTP pipeline to use for the service client. If {@code httpPipeline} is set, all other * settings are ignored. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving * responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpPipeline(HttpPipeline httpPipeline) { if (frozen) { throw LOGGER.logExceptionAsError(new IllegalStateException( "httpPipeline cannot be changed after any of the build methods have been called")); } this.httpPipeline = httpPipeline; return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param httpClient The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient httpClient) { if (frozen) { throw LOGGER.logExceptionAsError(new IllegalStateException( "httpClient cannot be changed after any of the build methods have been called")); } this.httpClient = httpClient; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param httpLogOptions The logging configuration to use when sending and receiving HTTP * requests/responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param httpPipelinePolicy a policy to be added to the http pipeline. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addHttpPipelinePolicy(HttpPipelinePolicy httpPipelinePolicy) { if (frozen) { throw LOGGER.logExceptionAsError(new IllegalStateException( "httpPipelinePolicies cannot be added after any of the build methods have been called")); } httpPipelinePolicies.add( Objects.requireNonNull(httpPipelinePolicy, "'policy' cannot be null.")); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { if (frozen) { throw LOGGER.logExceptionAsError(new IllegalStateException( "clientOptions cannot be changed after any of the build methods have been called")); } this.clientOptions = clientOptions; return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ public AzureMonitorExporterBuilder connectionString(String connectionString) { if (frozen) { throw LOGGER.logExceptionAsError(new IllegalStateException( "connectionString cannot be changed after any of the build methods have been called")); } this.connectionString = ConnectionString.parse(connectionString); return this; } /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion( AzureMonitorExporterServiceVersion serviceVersion) { if (frozen) { throw LOGGER.logExceptionAsError(new IllegalStateException( "serviceVersion cannot be changed after any of the build methods have been called")); } this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { if (frozen) { throw LOGGER.logExceptionAsError(new IllegalStateException( "credential cannot be changed after any of the build methods have been called")); } this.credential = credential; return this; } /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This * exporter is an implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the * environment variable "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public SpanExporter buildTraceExporter() { internalBuildAndFreeze(); return buildTraceExporter(DefaultConfigProperties.createForTest(Collections.emptyMap())); } /** * Creates an {@link AzureMonitorMetricExporter} based on the options set in the builder. This * exporter is an implementation of OpenTelemetry {@link MetricExporter}. * * <p>When a new {@link MetricExporter} is created, it will automatically start {@link * HeartbeatExporter}. * * @return An instance of {@link AzureMonitorMetricExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the * environment variable "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public MetricExporter buildMetricExporter() { internalBuildAndFreeze(); return buildMetricExporter(DefaultConfigProperties.createForTest(Collections.emptyMap())); } /** * Creates an {@link AzureMonitorLogRecordExporter} based on the options set in the builder. This * exporter is an implementation of OpenTelemetry {@link LogRecordExporter}. * * @return An instance of {@link AzureMonitorLogRecordExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the * environment variable "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public LogRecordExporter buildLogRecordExporter() { internalBuildAndFreeze(); return buildLogRecordExporter(DefaultConfigProperties.createForTest(Collections.emptyMap())); } /** * Configures an {@link AutoConfiguredOpenTelemetrySdkBuilder} based on the options set in the builder. * * @param sdkBuilder the {@link AutoConfiguredOpenTelemetrySdkBuilder} in which to install the azure monitor exporter. */ public void build(AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder) { internalBuildAndFreeze(); sdkBuilder.addPropertiesSupplier(() -> { Map<String, String> props = new HashMap<>(); props.put("otel.traces.exporter", AzureMonitorExporterProviderKeys.EXPORTER_NAME); props.put("otel.metrics.exporter", AzureMonitorExporterProviderKeys.EXPORTER_NAME); props.put("otel.logs.exporter", AzureMonitorExporterProviderKeys.EXPORTER_NAME); props.put(AzureMonitorExporterProviderKeys.INTERNAL_USING_AZURE_MONITOR_EXPORTER_BUILDER, "true"); return props; }); sdkBuilder.addSpanExporterCustomizer( (spanExporter, configProperties) -> { if (spanExporter instanceof AzureMonitorSpanExporterProvider.MarkerSpanExporter) { spanExporter = buildTraceExporter(configProperties); } return spanExporter; }); sdkBuilder.addMetricExporterCustomizer( (metricExporter, configProperties) -> { if (metricExporter instanceof AzureMonitorMetricExporterProvider.MarkerMetricExporter) { metricExporter = buildMetricExporter(configProperties); } return metricExporter; }); sdkBuilder.addLogRecordExporterCustomizer( (logRecordExporter, configProperties) -> { if (logRecordExporter instanceof AzureMonitorLogRecordExporterProvider.MarkerLogRecordExporter) { logRecordExporter = buildLogRecordExporter(configProperties); } return logRecordExporter; }); sdkBuilder.addMeterProviderCustomizer((sdkMeterProviderBuilder, configProperties) -> sdkMeterProviderBuilder.registerView( InstrumentSelector.builder() .setMeterName("io.opentelemetry.sdk.trace") .build(), View.builder() .setAggregation(Aggregation.drop()) .build() ).registerView( InstrumentSelector.builder() .setMeterName("io.opentelemetry.sdk.logs") .build(), View.builder() .setAggregation(Aggregation.drop()) .build() )); } private void internalBuildAndFreeze() { if (!frozen) { builtHttpPipeline = createHttpPipeline(); builtTelemetryItemExporter = createTelemetryItemExporter(); frozen = true; } } private SpanExporter buildTraceExporter(ConfigProperties configProperties) { return new AzureMonitorTraceExporter(createSpanDataMapper(configProperties), builtTelemetryItemExporter); } private MetricExporter buildMetricExporter(ConfigProperties configProperties) { HeartbeatExporter.start( MINUTES.toSeconds(15), createDefaultsPopulator(configProperties), builtTelemetryItemExporter::send); return new AzureMonitorMetricExporter( new MetricDataMapper(createDefaultsPopulator(configProperties), true), builtTelemetryItemExporter); } private LogRecordExporter buildLogRecordExporter(ConfigProperties configProperties) { return new AzureMonitorLogRecordExporter( new LogDataMapper(true, false, createDefaultsPopulator(configProperties)), builtTelemetryItemExporter); } private SpanDataMapper createSpanDataMapper(ConfigProperties configProperties) { return new SpanDataMapper( true, createDefaultsPopulator(configProperties), (event, instrumentationName) -> false, (span, event) -> false); } private BiConsumer<AbstractTelemetryBuilder, Resource> createDefaultsPopulator(ConfigProperties configProperties) { ConnectionString connectionString = getConnectionString(configProperties); return (builder, resource) -> { builder.setConnectionString(connectionString); builder.setResource(resource); builder.addTag( ContextTagKeys.AI_INTERNAL_SDK_VERSION.toString(), VersionGenerator.getSdkVersion()); ResourceParser.updateRoleNameAndInstance(builder, resource, configProperties); }; } private ConnectionString getConnectionString(ConfigProperties configProperties) { if (connectionString != null) { return connectionString; } ConnectionString connectionString = ConnectionString.parse(configProperties.getString(APPLICATIONINSIGHTS_CONNECTION_STRING)); return Objects.requireNonNull(connectionString, "'connectionString' cannot be null"); } private HttpPipeline createHttpPipeline() { if (httpPipeline != null) { if (credential != null) { throw LOGGER.logExceptionAsError(new IllegalStateException( "'credential' is not supported when custom 'httpPipeline' is specified")); } if (httpClient != null) { throw LOGGER.logExceptionAsError(new IllegalStateException( "'httpClient' is not supported when custom 'httpPipeline' is specified")); } if (httpLogOptions != null) { throw LOGGER.logExceptionAsError(new IllegalStateException( "'httpLogOptions' is not supported when custom 'httpPipeline' is specified")); } if (!httpPipelinePolicies.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalStateException( "'httpPipelinePolicies' is not supported when custom 'httpPipeline' is specified")); } if (clientOptions != null) { throw LOGGER.logExceptionAsError(new IllegalStateException( "'clientOptions' is not supported when custom 'httpPipeline' is specified")); } return httpPipeline; } List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault("name", "UnknownName"); String clientVersion = PROPERTIES.getOrDefault("version", "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(clientOptions, httpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, Configuration.getGlobalConfiguration())); policies.add(new CookiePolicy()); if (credential != null) { policies.add(new BearerTokenAuthenticationPolicy(credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE)); } policies.addAll(httpPipelinePolicies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new com.azure.core.http.HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(new NoopTracer()) .build(); } private TelemetryItemExporter createTelemetryItemExporter() { TelemetryPipeline pipeline = new TelemetryPipeline(builtHttpPipeline); File tempDir = TempDirs.getApplicationInsightsTempDir( LOGGER, "Telemetry will not be stored to disk and retried on sporadic network failures"); TelemetryItemExporter telemetryItemExporter; if (tempDir != null) { telemetryItemExporter = new TelemetryItemExporter( pipeline, new LocalStorageTelemetryPipelineListener( 50, TempDirs.getSubDir(tempDir, "telemetry"), pipeline, LocalStorageStats.noop(), false)); } else { telemetryItemExporter = new TelemetryItemExporter( pipeline, TelemetryPipelineListener.noop()); } return telemetryItemExporter; } }
we should add a unit test for redactinfo for this specific case to ensure it doesn't break in future.
AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; }
IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage()));
AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder .logPii(options.isSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder .validateAuthority(false) .logPii(options.isSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl) .logPii(options.isSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azdCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError( new IllegalStateException( "A Safe Working directory could not be" + " found to execute Azure Developer CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(options.getClientOptions(), httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); if (options.getClientOptions() != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); options.getClientOptions().getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder .logPii(options.isSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder .validateAuthority(false) .logPii(options.isSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl) .logPii(options.isSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azdCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError( new IllegalStateException( "A Safe Working directory could not be" + " found to execute Azure Developer CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(options.getClientOptions(), httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); if (options.getClientOptions() != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); options.getClientOptions().getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } }
A simple test.
public void testDeploymentStacks() { final String dpName = "dpA" + testId; DeploymentStackInner deploymentStack = resourceClient.deploymentStackClient().getDeploymentStacks() .createOrUpdateAtResourceGroup(rgName, dpName, new DeploymentStackInner() .withTags(Collections.singletonMap("usage", "test")) .withTemplateLink( new DeploymentStacksTemplateLink() .withUri(TEMPLATE_URI) .withContentVersion(CONTENT_VERSION)) .withParametersLink( new DeploymentStacksParametersLink() .withUri(PARAMETERS_URI) .withContentVersion(CONTENT_VERSION)) .withActionOnUnmanage( new DeploymentStackPropertiesActionOnUnmanage() .withResources(DeploymentStacksDeleteDetachEnum.DELETE) .withResourceGroups(DeploymentStacksDeleteDetachEnum.DETACH) .withManagementGroups(DeploymentStacksDeleteDetachEnum.DETACH)) .withDenySettings(new DenySettings() .withMode(DenySettingsMode.NONE))); Assertions.assertEquals(dpName, deploymentStack.name()); Assertions.assertEquals(DeploymentStacksDeleteDetachEnum.DELETE, deploymentStack.actionOnUnmanage().resources()); deploymentStack = resourceClient.deploymentStackClient().getDeploymentStacks() .getByResourceGroup(rgName, dpName); Assertions.assertEquals(dpName, deploymentStack.name()); Assertions.assertEquals(DeploymentStacksDeleteDetachEnum.DELETE, deploymentStack.actionOnUnmanage().resources()); }
.withMode(DenySettingsMode.NONE)));
public void testDeploymentStacks() { final String dpName = "dpA" + testId; DeploymentStackInner deploymentStack = resourceClient.deploymentStackClient().getDeploymentStacks() .createOrUpdateAtResourceGroup(rgName, dpName, new DeploymentStackInner() .withTags(Collections.singletonMap("usage", "test")) .withTemplateLink( new DeploymentStacksTemplateLink() .withUri(TEMPLATE_URI) .withContentVersion(CONTENT_VERSION)) .withParametersLink( new DeploymentStacksParametersLink() .withUri(PARAMETERS_URI) .withContentVersion(CONTENT_VERSION)) .withActionOnUnmanage( new DeploymentStackPropertiesActionOnUnmanage() .withResources(DeploymentStacksDeleteDetachEnum.DELETE) .withResourceGroups(DeploymentStacksDeleteDetachEnum.DETACH) .withManagementGroups(DeploymentStacksDeleteDetachEnum.DETACH)) .withDenySettings(new DenySettings() .withMode(DenySettingsMode.NONE))); Assertions.assertEquals(dpName, deploymentStack.name()); Assertions.assertEquals(DeploymentStacksDeleteDetachEnum.DELETE, deploymentStack.actionOnUnmanage().resources()); deploymentStack = resourceClient.deploymentStackClient().getDeploymentStacks() .getByResourceGroup(rgName, dpName); Assertions.assertEquals(dpName, deploymentStack.name()); Assertions.assertEquals(DeploymentStacksDeleteDetachEnum.DELETE, deploymentStack.actionOnUnmanage().resources()); }
class DeploymentStacksTests extends ResourceManagementTest { private ResourceGroups resourceGroups; private String testId; private String rgName; private static final Region REGION = Region.US_WEST3; private static final String TEMPLATE_URI = "https: private static final String PARAMETERS_URI = "https: private static final String CONTENT_VERSION = "1.0.0.0"; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { super.initializeClients(httpPipeline, profile); testId = generateRandomResourceName("", 9); resourceGroups = resourceClient.resourceGroups(); rgName = "rg" + testId; resourceGroups.define(rgName) .withRegion(REGION) .create(); } @Override protected void cleanUpResources() { resourceGroups.beginDeleteByName(rgName); } @DoNotRecord(skipInPlayback = true) @Test }
class DeploymentStacksTests extends ResourceManagementTest { private ResourceGroups resourceGroups; private String testId; private String rgName; private static final Region REGION = Region.US_WEST3; private static final String TEMPLATE_URI = "https: private static final String PARAMETERS_URI = "https: private static final String CONTENT_VERSION = "1.0.0.0"; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { super.initializeClients(httpPipeline, profile); testId = generateRandomResourceName("", 9); resourceGroups = resourceClient.resourceGroups(); rgName = "rg" + testId; resourceGroups.define(rgName) .withRegion(REGION) .create(); } @Override protected void cleanUpResources() { resourceGroups.beginDeleteByName(rgName); } @DoNotRecord(skipInPlayback = true) @Test }
Is deallocate required?
public void canUpdateDeleteOptions() { String networkName = generateRandomResourceName("network", 15); String nicName = generateRandomResourceName("nic", 15); String nicName2 = generateRandomResourceName("nic", 15); Network network = this .networkManager .networks() .define(networkName) .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.1.0/24") .withSubnet("subnet1", "10.0.1.0/28") .withSubnet("subnet2", "10.0.1.16/28") .create(); VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet1") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_20_04_LTS_GEN2) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withNewDataDisk(10, 1, new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DELETE)) .withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2) .withNewSecondaryNetworkInterface(this .networkManager .networkInterfaces() .define(nicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet1") .withPrimaryPrivateIPAddressDynamic(), DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertEquals(DeleteOptions.DELETE, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); vm.update() .withOsDiskDeleteOptions(DeleteOptions.DETACH) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DETACH) .withDataDiskDeleteOptions(1, DeleteOptions.DETACH) .withNewDataDisk(1) .apply(); Assertions.assertEquals(DeleteOptions.DETACH, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.networkInterfaceIds().stream() .filter(nicId -> !nicId.equals(vm.primaryNetworkInterfaceId())).allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DETACH.equals(disk.deleteOptions()))); NetworkInterface secondaryNic2 = this .networkManager .networkInterfaces() .define(nicName2) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet2") .withPrimaryPrivateIPAddressDynamic() .create(); vm.powerOff(); vm.deallocate(); vm.update() .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withDataDisksDeleteOptions(DeleteOptions.DELETE) .withNewDataDisk(1) .withSecondaryNetworkInterfacesDeleteOptions(DeleteOptions.DELETE) .withExistingSecondaryNetworkInterface(secondaryNic2) .apply(); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.networkInterfaceIds().stream().allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); }
vm.deallocate();
public void canUpdateDeleteOptions() { String networkName = generateRandomResourceName("network", 15); String nicName = generateRandomResourceName("nic", 15); String nicName2 = generateRandomResourceName("nic", 15); Network network = this .networkManager .networks() .define(networkName) .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.1.0/24") .withSubnet("subnet1", "10.0.1.0/28") .withSubnet("subnet2", "10.0.1.16/28") .create(); VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet1") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_20_04_LTS_GEN2) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withNewDataDisk(10, 1, new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DELETE)) .withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2) .withNewSecondaryNetworkInterface(this .networkManager .networkInterfaces() .define(nicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet1") .withPrimaryPrivateIPAddressDynamic(), DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertEquals(DeleteOptions.DELETE, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); vm.update() .withOsDiskDeleteOptions(DeleteOptions.DETACH) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DETACH) .withDataDisksDeleteOptions(DeleteOptions.DETACH, 1) .apply(); Assertions.assertEquals(DeleteOptions.DETACH, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.networkInterfaceIds().stream() .filter(nicId -> !nicId.equals(vm.primaryNetworkInterfaceId())).allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DETACH.equals(disk.deleteOptions()))); NetworkInterface secondaryNic2 = this .networkManager .networkInterfaces() .define(nicName2) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet2") .withPrimaryPrivateIPAddressDynamic() .create(); vm.powerOff(); vm.deallocate(); vm.update() .withNewDataDisk(1, 2, new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DETACH)) .withExistingSecondaryNetworkInterface(secondaryNic2) .apply(); vm.update() .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withDataDisksDeleteOptions(DeleteOptions.DELETE, new ArrayList<>(vm.dataDisks().keySet()).toArray(new Integer[0])) .withNetworkInterfacesDeleteOptions( DeleteOptions.DELETE, vm.networkInterfaceIds().stream().filter(nic -> !nic.equals(vm.primaryNetworkInterfaceId())).toArray(String[]::new)) .apply(); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.networkInterfaceIds().stream().allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); }
class VirtualMachineOperationsTests extends ComputeManagementTest { private String rgName = ""; private String rgName2 = ""; private final Region region = Region.US_EAST; private final Region regionProxPlacementGroup = Region.US_WEST; private final Region regionProxPlacementGroup2 = Region.US_EAST; private final String vmName = "javavm"; private final String proxGroupName = "testproxgroup1"; private final String proxGroupName2 = "testproxgroup2"; private final String availabilitySetName = "availset1"; private final String availabilitySetName2 = "availset2"; private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); rgName2 = generateRandomResourceName("javacsmrg2", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName != null) { resourceManager.resourceGroups().beginDeleteByName(rgName); } } @Test public void canCreateVirtualMachineWithNetworking() throws Exception { NetworkSecurityGroup nsg = this .networkManager .networkSecurityGroups() .define("nsg") .withRegion(region) .withNewResourceGroup(rgName) .defineRule("rule1") .allowInbound() .fromAnyAddress() .fromPort(80) .toAnyAddress() .toPort(80) .withProtocol(SecurityRuleProtocol.TCP) .attach() .create(); Creatable<Network> networkDefinition = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .defineSubnet("subnet1") .withAddressPrefix("10.0.0.0/29") .withExistingNetworkSecurityGroup(nsg) .attach(); VirtualMachine vm = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork(networkDefinition) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .create(); NetworkInterface primaryNic = vm.getPrimaryNetworkInterface(); Assertions.assertNotNull(primaryNic); NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration(); Assertions.assertNotNull(primaryIpConfig); Assertions.assertNotNull(primaryIpConfig.networkId()); Network network = primaryIpConfig.getNetwork(); Assertions.assertNotNull(primaryIpConfig.subnetName()); Subnet subnet = network.subnets().get(primaryIpConfig.subnetName()); Assertions.assertNotNull(subnet); nsg = subnet.getNetworkSecurityGroup(); Assertions.assertNotNull(nsg); Assertions.assertEquals("nsg", nsg.name()); Assertions.assertEquals(1, nsg.securityRules().size()); nsg = primaryIpConfig.getNetworkSecurityGroup(); Assertions.assertEquals("nsg", nsg.name()); } @Test public void canCreateVirtualMachine() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertNotNull(foundVM.timeCreated()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotCreateVirtualMachineSyncPoll() throws Exception { final String mySqlInstallScript = "https: final String installCommand = "bash install_mysql_server_5.6.sh Abc.123x("; Assertions.assertThrows(IllegalStateException.class, () -> { Accepted<VirtualMachine> acceptedVirtualMachine = this.computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .defineNewExtension("CustomScriptForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("CustomScriptForLinux") .withVersion("1.4") .withMinorVersionAutoUpgrade() .withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript)) .withPublicSetting("commandToExecute", installCommand) .attach() .beginCreate(); }); boolean dependentResourceCreated = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName); Assertions.assertFalse(dependentResourceCreated); rgName = null; } @Test public void canCreateVirtualMachineSyncPoll() throws Exception { final long defaultDelayInMillis = 10 * 1000; Accepted<VirtualMachine> acceptedVirtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .beginCreate(); VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue(); Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState()); LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus(); long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills)); PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult(); Assertions.assertEquals("Succeeded", virtualMachine.provisioningState()); Accepted<Void> acceptedDelete = computeManager.virtualMachines() .beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name()); pollStatus = acceptedDelete.getActivationResponse().getStatus(); delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills)); PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : (int) pollResponse.getRetryAfter().toMillis(); } boolean deleted = false; try { computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException e) { if (e.getResponse().getStatusCode() == 404 && ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) { deleted = true; } } Assertions.assertTrue(deleted); } @Test public void canCreateUpdatePriorityAndPrice() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withMaxPrice(1000.0) .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice()); Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy()); try { foundVM.update().withMaxPrice(1500.0).apply(); Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice()); Assertions.fail(); } catch (ManagementException e) { } foundVM.deallocate(); foundVM.update().withMaxPrice(2000.0).apply(); foundVM.start(); Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority()); try { foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority()); Assertions.fail(); } catch (ManagementException e) { } computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); AvailabilitySet setCreated2 = computeManager .availabilitySets() .define(availabilitySetName2) .withRegion(regionProxPlacementGroup2) .withNewResourceGroup(rgName2) .withNewProximityPlacementGroup(proxGroupName2, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName2, setCreated2.name()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); try { VirtualMachine updatedVm = foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply(); } catch (ManagementException clEx) { Assertions .assertTrue( clEx .getMessage() .contains( "Updating proximity placement group of VM javavm is not allowed while the VM is running." + " Please stop/deallocate the VM and retry the operation.")); } computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply(); Assertions.assertNotNull(updatedVm.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0))); computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys; List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys; CreatedResources<VirtualMachine> createdVirtualMachines = computeManager.virtualMachines().create(virtualMachineCreatables); Assertions.assertTrue(createdVirtualMachines.size() == count); Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } for (VirtualMachine virtualMachine : createdVirtualMachines.values()) { Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } for (String networkCreatableKey : networkCreatableKeys) { Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey); Assertions.assertNotNull(createdNetwork); Assertions.assertTrue(networkNames.contains(createdNetwork.name())); } Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } for (String publicIpCreatableKey : publicIpCreatableKeys) { PublicIpAddress createdPublicIpAddress = (PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey); Assertions.assertNotNull(createdPublicIpAddress); Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name())); } } @Test public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; final Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } final Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } final Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } final CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); final AtomicInteger resourceCount = new AtomicInteger(0); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; computeManager .virtualMachines() .createAsync(virtualMachineCreatables) .map( createdResource -> { if (createdResource instanceof Resource) { Resource resource = (Resource) createdResource; System.out.println("Created: " + resource.id()); if (resource instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine) resource; Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } else if (resource instanceof Network) { Network network = (Network) resource; Assertions.assertTrue(networkNames.contains(network.name())); Assertions.assertNotNull(network.id()); } else if (resource instanceof PublicIpAddress) { PublicIpAddress publicIPAddress = (PublicIpAddress) resource; Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name())); Assertions.assertNotNull(publicIPAddress.id()); } } resourceCount.incrementAndGet(); return createdResource; }) .blockLast(); networkNames.forEach(name -> { Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name)); }); publicIPAddressNames.forEach(name -> { Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name)); }); Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, resourceCount.get()); } @Test public void canSetStorageAccountForUnmanagedDisk() { final String storageName = generateRandomResourceName("st", 14); StorageAccount storageAccount = storageManager .storageAccounts() .define(storageName) .withRegion(region) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.PREMIUM_LRS) .create(); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withUnmanagedDisks() .defineUnmanagedDataDisk("disk1") .withNewVhd(100) .withLun(2) .storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .attach() .defineUnmanagedDataDisk("disk2") .withNewVhd(100) .withLun(3) .storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .attach() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .create(); Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2); Assertions.assertNotNull(firstUnmanagedDataDisk); VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3); Assertions.assertNotNull(secondUnmanagedDataDisk); String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri(); String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri(); Assertions.assertNotNull(createdVhdUri1); Assertions.assertNotNull(createdVhdUri2); computeManager.virtualMachines().deleteById(virtualMachine.id()); virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withUnmanagedDisks() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(1, unmanagedDataDisks.size()); firstUnmanagedDataDisk = null; for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) { firstUnmanagedDataDisk = unmanagedDisk; break; } Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri()); Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1)); virtualMachine .update() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .apply(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); } @Test public void canUpdateTagsOnVM() { VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); virtualMachine.update().withTag("test", "testValue").apply(); Assertions.assertEquals("testValue", virtualMachine.innerModel().tags().get("test")); Map<String, String> testTags = new HashMap<String, String>(); testTags.put("testTag", "testValue"); virtualMachine.update().withTags(testTags).apply(); Assertions.assertEquals(testTags.get("testTag"), virtualMachine.innerModel().tags().get("testTag")); } @Test public void canRunScriptOnVM() { VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .create(); List<String> installGit = new ArrayList<>(); installGit.add("sudo apt-get update"); installGit.add("sudo apt-get install -y git"); RunCommandResult runResult = virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>()); Assertions.assertNotNull(runResult); Assertions.assertNotNull(runResult.value()); Assertions.assertTrue(runResult.value().size() > 0); } @Test @DoNotRecord(skipInPlayback = true) public void canPerformSimulateEvictionOnSpotVirtualMachine() { VirtualMachine virtualMachine = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertTrue(virtualMachine.osDiskSize() > 0); Disk disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertNotNull(disk); Assertions.assertEquals(DiskState.ATTACHED, disk.innerModel().diskState()); virtualMachine.simulateEviction(); boolean deallocated = false; int pollIntervalInMinutes = 5; for (int i = 0; i < 30; i += pollIntervalInMinutes) { ResourceManagerUtils.sleep(Duration.ofMinutes(pollIntervalInMinutes)); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); if (virtualMachine.powerState() == PowerState.DEALLOCATED) { deallocated = true; break; } } Assertions.assertTrue(deallocated); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); Assertions.assertNotNull(virtualMachine); Assertions.assertNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertEquals(0, virtualMachine.osDiskSize()); disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertEquals(DiskState.RESERVED, disk.innerModel().diskState()); } @Test public void canForceDeleteVirtualMachine() { computeManager.virtualMachines() .define(vmName) .withRegion("eastus2euap") .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .create(); VirtualMachine virtualMachine = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(virtualMachine); Assertions.assertEquals(Region.fromName("eastus2euap"), virtualMachine.region()); String nicId = virtualMachine.primaryNetworkInterfaceId(); computeManager.virtualMachines().deleteById(virtualMachine.id(), true); try { virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException ex) { virtualMachine = null; Assertions.assertEquals(404, ex.getResponse().getStatusCode()); } Assertions.assertNull(virtualMachine); NetworkInterface nic = networkManager.networkInterfaces().getById(nicId); Assertions.assertNotNull(nic); } @Test public void canCreateVirtualMachineWithDeleteOption() throws Exception { Region region = Region.US_WEST3; final String publicIpDnsLabel = generateRandomResourceName("pip", 20); Network network = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("default", "10.0.0.0/24") .create(); VirtualMachine vm1 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel/*, DeleteOptions.DELETE*/) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withNewDataDisk(computeManager.disks() .define("datadisk2") .withRegion(region) .withExistingResourceGroup(rgName) .withData() .withSizeInGB(10)) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(DeleteOptions.DELETE, vm1.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(0).deleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(1).deleteOptions()); Assertions.assertEquals(vm1.id(), computeManager.virtualMachines().getById(vm1.id()).id()); computeManager.virtualMachines().deleteById(vm1.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(2, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); PublicIpAddress publicIpAddress = computeManager.networkManager().publicIpAddresses().listByResourceGroup(rgName).stream().findFirst().get(); computeManager.networkManager().publicIpAddresses().deleteById(publicIpAddress.id()); String secondaryNicName = generateRandomResourceName("nic", 10); Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable = this .networkManager .networkInterfaces() .define(secondaryNicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic(); VirtualMachine vm2 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable, DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); computeManager.virtualMachines().deleteById(vm2.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(1, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); secondaryNetworkInterfaceCreatable = this .networkManager .networkInterfaces() .define(secondaryNicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic(); VirtualMachine vm3 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withNewDataDisk(computeManager.disks() .define("datadisk2") .withRegion(region) .withExistingResourceGroup(rgName) .withData() .withSizeInGB(10)) .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(DeleteOptions.DETACH, vm3.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(0).deleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(1).deleteOptions()); computeManager.virtualMachines().deleteById(vm3.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(3, computeManager.disks().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(2, computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count()); } @Test public void canUpdateVirtualMachineWithDeleteOption() throws Exception { Region region = Region.US_WEST3; Network network = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("default", "10.0.0.0/24") .create(); VirtualMachine vm1 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); vm1.update() .withNewDataDisk(10) .apply(); computeManager.virtualMachines().deleteById(vm1.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(1, computeManager.disks().listByResourceGroup(rgName).stream().count()); Disk disk = computeManager.disks().listByResourceGroup(rgName).stream().findFirst().get(); computeManager.disks().deleteById(disk.id()); VirtualMachine vm2 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); vm2.update() .withNewDataDisk(10) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .apply(); computeManager.virtualMachines().deleteById(vm2.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(2, computeManager.disks().listByResourceGroup(rgName).stream().count()); } @Test public void canHibernateVirtualMachine() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion("eastus2euap") .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3) .enableHibernation() .create(); Assertions.assertTrue(vm.isHibernationEnabled()); vm.deallocate(true); InstanceViewStatus hibernationStatus = vm.instanceView().statuses().stream() .filter(status -> "HibernationState/Hibernated".equals(status.code())) .findFirst().orElse(null); Assertions.assertNotNull(hibernationStatus); vm.start(); vm.deallocate(); vm.update() .disableHibernation() .apply(); Assertions.assertFalse(vm.isHibernationEnabled()); } @Test public void canOperateVirtualMachine() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.redeploy(); vm.powerOff(true); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.STOPPED, vm.powerState()); vm.start(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.restart(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.deallocate(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.DEALLOCATED, vm.powerState()); } @Test public void canCreateVirtualMachineWithEphemeralOSDisk() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) .withEphemeralOSDisk() .withPlacement(DiffDiskPlacement.CACHE_DISK) .withNewDataDisk(1, 1, CachingTypes.READ_WRITE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertNull(vm.osDiskDiskEncryptionSetId()); Assertions.assertTrue(vm.osDiskSize() > 0); Assertions.assertEquals(vm.osDiskDeleteOptions(), DeleteOptions.DELETE); Assertions.assertEquals(vm.osDiskCachingType(), CachingTypes.READ_ONLY); Assertions.assertFalse(CoreUtils.isNullOrEmpty(vm.dataDisks())); Assertions.assertTrue(vm.isOSDiskEphemeral()); Assertions.assertNotNull(vm.osDiskId()); String osDiskId = vm.osDiskId(); vm.update() .withoutDataDisk(1) .withNewDataDisk(1, 2, CachingTypes.NONE) .withNewDataDisk(1) .apply(); Assertions.assertEquals(vm.dataDisks().size(), 2); vm.powerOff(); vm.start(); vm.refresh(); Assertions.assertEquals(osDiskId, vm.osDiskId()); Assertions.assertThrows(Exception.class, vm::deallocate); } @Test public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { final String vmssName = generateRandomResourceName("vmss", 10); Network network = this .networkManager .networks() .define("vmssvnet") .withRegion(region.name()) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().getByName(rgName); LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); VirtualMachineScaleSet flexibleVMSS = this.computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(rgName) .withFlexibleOrchestrationMode() .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_DS1_V2) .withExistingPrimaryNetworkSubnet(network, "subnet1") .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .withoutPrimaryInternalLoadBalancer() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withCapacity(1) .withUpgradeMode(UpgradeMode.AUTOMATIC) .create(); String regularVMName = generateRandomResourceName("vm", 10); final String pipDnsLabel = generateRandomResourceName("pip", 10); VirtualMachine regularVM = this.computeManager .virtualMachines() .define(regularVMName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(pipDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("jvuser2") .withSsh(sshPublicKey()) .withExistingVirtualMachineScaleSet(flexibleVMSS) .create(); flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.id(), regularVM.virtualMachineScaleSetId()); Assertions.assertEquals(2, flexibleVMSS.capacity()); regularVM.deallocate(); Assertions.assertEquals(regularVM.powerState(), PowerState.DEALLOCATED); this.computeManager .virtualMachines().deleteById(regularVM.id()); flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.capacity(), 1); final String storageAccountName = generateRandomResourceName("stg", 17); Assertions.assertThrows( ApiErrorException.class, () -> computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withLatestLinuxImage("Canonical", "UbuntuServer", "14.04.2-LTS") .withRootUsername("jvuser3") .withSsh(sshPublicKey()) .withUnmanagedDisks() /* UN-MANAGED OS and DATA DISKS */ .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withNewStorageAccount(storageAccountName) .withOSDiskCaching(CachingTypes.READ_WRITE) .withExistingVirtualMachineScaleSet(flexibleVMSS) .create() ); final String vmssName2 = generateRandomResourceName("vmss", 10); Network network2 = this .networkManager .networks() .define("vmssvnet2") .withRegion(region.name()) .withExistingResourceGroup(rgName) .withAddressSpace("192.168.0.0/28") .withSubnet("subnet2", "192.168.0.0/28") .create(); LoadBalancer publicLoadBalancer2 = createHttpLoadBalancers(region, resourceGroup, "2", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); VirtualMachineScaleSet uniformVMSS = this.computeManager .virtualMachineScaleSets() .define(vmssName2) .withRegion(region) .withNewResourceGroup(rgName) .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) .withExistingPrimaryNetworkSubnet(network2, "subnet2") .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer2) .withoutPrimaryInternalLoadBalancer() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser4") .withSsh(sshPublicKey()) .withCapacity(1) .create(); Assertions.assertTrue(uniformVMSS.virtualMachines().list().stream().allMatch(v -> v.instanceId() != null)); String regularVMName2 = generateRandomResourceName("vm", 10); Assertions.assertThrows( ApiErrorException.class, () -> this.computeManager .virtualMachines() .define(regularVMName2) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("jvuser5") .withSsh(sshPublicKey()) .withExistingVirtualMachineScaleSet(uniformVMSS) .create() ); } @Test @DoNotRecord(skipInPlayback = true) public void canSwapOSDiskWithManagedDisk() { String storageAccountName = generateRandomResourceName("sa", 15); StorageAccount storageAccount = this.storageManager .storageAccounts() .define(storageAccountName) .withRegion(region) .withNewResourceGroup(rgName) .create(); String vm1Name = generateRandomResourceName("vm", 15); VirtualMachine vm1 = this.computeManager .virtualMachines() .define(vm1Name) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/24") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withNewDataDisk(10, 1, CachingTypes.READ_WRITE) .withOSDiskDeleteOptions(DeleteOptions.DETACH) .withExistingStorageAccount(storageAccount) .create(); Disk vm1OSDisk = this.computeManager.disks().getById(vm1.osDiskId()); Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_KEY, vm1OSDisk.encryption().type()); String vaultName = generateRandomResourceName("vault", 15); Vault vault = this.keyVaultManager .vaults() .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowKeyPermissions(KeyPermissions.CREATE) .attach() .create(); String keyName = generateRandomResourceName("key", 15); Key key = vault.keys() .define(keyName) .withKeyTypeToCreate(KeyType.RSA) .withKeySize(4096) .create(); String desName = generateRandomResourceName("des", 15); DiskEncryptionSet des = this.computeManager.diskEncryptionSets() .define(desName) .withRegion(region) .withExistingResourceGroup(rgName) .withEncryptionType(DiskEncryptionSetType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY) .withExistingKeyVault(vault.id()) .withExistingKey(key.id()) .withSystemAssignedManagedServiceIdentity() .create(); vault.update() .defineAccessPolicy() .forObjectId(des.systemAssignedManagedServiceIdentityPrincipalId()) .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.UNWRAP_KEY, KeyPermissions.WRAP_KEY) .attach() .withPurgeProtectionEnabled() .apply(); String vm2Name = generateRandomResourceName("vm", 15); VirtualMachine vm2 = this.computeManager.virtualMachines() .define(vm2Name) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/24") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withOSDiskDiskEncryptionSet(des.id()) .withOSDiskDeleteOptions(DeleteOptions.DETACH) .create(); String vm2OSDiskId = vm2.osDiskId(); this.computeManager.virtualMachines().deleteById(vm2.id()); Disk vm2OSDisk = this.computeManager.disks().getById(vm2OSDiskId); Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY, vm2OSDisk.encryption().type()); vm1.deallocate(); vm1.update() .withOSDisk(vm2OSDiskId) .apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm2OSDiskId); Assertions.assertTrue(des.id().equalsIgnoreCase(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet().id())); vm1.deallocate(); vm1.update() .withOSDisk(vm1OSDisk) .apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm1OSDisk.id()); Assertions.assertNull(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet()); } @Test public void canCRUDTrustedLaunchVM() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_20_04_LTS_GEN2) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withTrustedLaunch() .withSecureBoot() .withVTpm() .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertEquals(SecurityTypes.TRUSTED_LAUNCH, vm.securityType()); Assertions.assertTrue(vm.isSecureBootEnabled()); Assertions.assertTrue(vm.isVTpmEnabled()); vm.update() .withoutSecureBoot() .withoutVTpm() .applyAsync() .flatMap(VirtualMachine::restartAsync) .block(); ResourceManagerUtils.sleep(Duration.ofMinutes(1)); vm = computeManager.virtualMachines().getById(vm.id()); Assertions.assertEquals(SecurityTypes.TRUSTED_LAUNCH, vm.securityType()); Assertions.assertFalse(vm.isSecureBootEnabled()); Assertions.assertFalse(vm.isVTpmEnabled()); computeManager.virtualMachines().deleteById(vm.id()); } @Test private CreatablesInfo prepareCreatableVirtualMachines( Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) { Creatable<ResourceGroup> resourceGroupCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); Creatable<StorageAccount> storageAccountCreatable = storageManager .storageAccounts() .define(generateRandomResourceName("stg", 20)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); List<String> networkCreatableKeys = new ArrayList<>(); List<String> publicIpCreatableKeys = new ArrayList<>(); List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>(); for (int i = 0; i < vmCount; i++) { Creatable<Network> networkCreatable = networkManager .networks() .define(String.format("%s-%d", networkNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withAddressSpace("10.0.0.0/28"); networkCreatableKeys.add(networkCreatable.key()); Creatable<PublicIpAddress> publicIPAddressCreatable = networkManager .publicIpAddresses() .define(String.format("%s-%d", publicIpNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); publicIpCreatableKeys.add(publicIPAddressCreatable.key()); Creatable<VirtualMachine> virtualMachineCreatable = computeManager .virtualMachines() .define(String.format("%s-%d", vmNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withNewPrimaryNetwork(networkCreatable) .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("tirekicker") .withSsh(sshPublicKey()) .withUnmanagedDisks() .withNewStorageAccount(storageAccountCreatable); virtualMachineCreatables.add(virtualMachineCreatable); } CreatablesInfo creatablesInfo = new CreatablesInfo(); creatablesInfo.virtualMachineCreatables = virtualMachineCreatables; creatablesInfo.networkCreatableKeys = networkCreatableKeys; creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys; return creatablesInfo; } class CreatablesInfo { private List<Creatable<VirtualMachine>> virtualMachineCreatables; List<String> networkCreatableKeys; List<String> publicIpCreatableKeys; } }
class VirtualMachineOperationsTests extends ComputeManagementTest { private String rgName = ""; private String rgName2 = ""; private final Region region = Region.US_EAST; private final Region regionProxPlacementGroup = Region.US_WEST; private final Region regionProxPlacementGroup2 = Region.US_EAST; private final String vmName = "javavm"; private final String proxGroupName = "testproxgroup1"; private final String proxGroupName2 = "testproxgroup2"; private final String availabilitySetName = "availset1"; private final String availabilitySetName2 = "availset2"; private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); rgName2 = generateRandomResourceName("javacsmrg2", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName != null) { resourceManager.resourceGroups().beginDeleteByName(rgName); } } @Test public void canCreateVirtualMachineWithNetworking() throws Exception { NetworkSecurityGroup nsg = this .networkManager .networkSecurityGroups() .define("nsg") .withRegion(region) .withNewResourceGroup(rgName) .defineRule("rule1") .allowInbound() .fromAnyAddress() .fromPort(80) .toAnyAddress() .toPort(80) .withProtocol(SecurityRuleProtocol.TCP) .attach() .create(); Creatable<Network> networkDefinition = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .defineSubnet("subnet1") .withAddressPrefix("10.0.0.0/29") .withExistingNetworkSecurityGroup(nsg) .attach(); VirtualMachine vm = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork(networkDefinition) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .create(); NetworkInterface primaryNic = vm.getPrimaryNetworkInterface(); Assertions.assertNotNull(primaryNic); NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration(); Assertions.assertNotNull(primaryIpConfig); Assertions.assertNotNull(primaryIpConfig.networkId()); Network network = primaryIpConfig.getNetwork(); Assertions.assertNotNull(primaryIpConfig.subnetName()); Subnet subnet = network.subnets().get(primaryIpConfig.subnetName()); Assertions.assertNotNull(subnet); nsg = subnet.getNetworkSecurityGroup(); Assertions.assertNotNull(nsg); Assertions.assertEquals("nsg", nsg.name()); Assertions.assertEquals(1, nsg.securityRules().size()); nsg = primaryIpConfig.getNetworkSecurityGroup(); Assertions.assertEquals("nsg", nsg.name()); } @Test public void canCreateVirtualMachine() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertNotNull(foundVM.timeCreated()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotCreateVirtualMachineSyncPoll() throws Exception { final String mySqlInstallScript = "https: final String installCommand = "bash install_mysql_server_5.6.sh Abc.123x("; Assertions.assertThrows(IllegalStateException.class, () -> { Accepted<VirtualMachine> acceptedVirtualMachine = this.computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .defineNewExtension("CustomScriptForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("CustomScriptForLinux") .withVersion("1.4") .withMinorVersionAutoUpgrade() .withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript)) .withPublicSetting("commandToExecute", installCommand) .attach() .beginCreate(); }); boolean dependentResourceCreated = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName); Assertions.assertFalse(dependentResourceCreated); rgName = null; } @Test public void canCreateVirtualMachineSyncPoll() throws Exception { final long defaultDelayInMillis = 10 * 1000; Accepted<VirtualMachine> acceptedVirtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .beginCreate(); VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue(); Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState()); LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus(); long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills)); PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult(); Assertions.assertEquals("Succeeded", virtualMachine.provisioningState()); Accepted<Void> acceptedDelete = computeManager.virtualMachines() .beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name()); pollStatus = acceptedDelete.getActivationResponse().getStatus(); delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills)); PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : (int) pollResponse.getRetryAfter().toMillis(); } boolean deleted = false; try { computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException e) { if (e.getResponse().getStatusCode() == 404 && ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) { deleted = true; } } Assertions.assertTrue(deleted); } @Test public void canCreateUpdatePriorityAndPrice() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withMaxPrice(1000.0) .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice()); Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy()); try { foundVM.update().withMaxPrice(1500.0).apply(); Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice()); Assertions.fail(); } catch (ManagementException e) { } foundVM.deallocate(); foundVM.update().withMaxPrice(2000.0).apply(); foundVM.start(); Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority()); try { foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority()); Assertions.fail(); } catch (ManagementException e) { } computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); AvailabilitySet setCreated2 = computeManager .availabilitySets() .define(availabilitySetName2) .withRegion(regionProxPlacementGroup2) .withNewResourceGroup(rgName2) .withNewProximityPlacementGroup(proxGroupName2, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName2, setCreated2.name()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); try { VirtualMachine updatedVm = foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply(); } catch (ManagementException clEx) { Assertions .assertTrue( clEx .getMessage() .contains( "Updating proximity placement group of VM javavm is not allowed while the VM is running." + " Please stop/deallocate the VM and retry the operation.")); } computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply(); Assertions.assertNotNull(updatedVm.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0))); computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys; List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys; CreatedResources<VirtualMachine> createdVirtualMachines = computeManager.virtualMachines().create(virtualMachineCreatables); Assertions.assertTrue(createdVirtualMachines.size() == count); Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } for (VirtualMachine virtualMachine : createdVirtualMachines.values()) { Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } for (String networkCreatableKey : networkCreatableKeys) { Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey); Assertions.assertNotNull(createdNetwork); Assertions.assertTrue(networkNames.contains(createdNetwork.name())); } Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } for (String publicIpCreatableKey : publicIpCreatableKeys) { PublicIpAddress createdPublicIpAddress = (PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey); Assertions.assertNotNull(createdPublicIpAddress); Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name())); } } @Test public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; final Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } final Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } final Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } final CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); final AtomicInteger resourceCount = new AtomicInteger(0); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; computeManager .virtualMachines() .createAsync(virtualMachineCreatables) .map( createdResource -> { if (createdResource instanceof Resource) { Resource resource = (Resource) createdResource; System.out.println("Created: " + resource.id()); if (resource instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine) resource; Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } else if (resource instanceof Network) { Network network = (Network) resource; Assertions.assertTrue(networkNames.contains(network.name())); Assertions.assertNotNull(network.id()); } else if (resource instanceof PublicIpAddress) { PublicIpAddress publicIPAddress = (PublicIpAddress) resource; Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name())); Assertions.assertNotNull(publicIPAddress.id()); } } resourceCount.incrementAndGet(); return createdResource; }) .blockLast(); networkNames.forEach(name -> { Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name)); }); publicIPAddressNames.forEach(name -> { Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name)); }); Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, resourceCount.get()); } @Test public void canSetStorageAccountForUnmanagedDisk() { final String storageName = generateRandomResourceName("st", 14); StorageAccount storageAccount = storageManager .storageAccounts() .define(storageName) .withRegion(region) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.PREMIUM_LRS) .create(); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withUnmanagedDisks() .defineUnmanagedDataDisk("disk1") .withNewVhd(100) .withLun(2) .storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .attach() .defineUnmanagedDataDisk("disk2") .withNewVhd(100) .withLun(3) .storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .attach() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .create(); Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2); Assertions.assertNotNull(firstUnmanagedDataDisk); VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3); Assertions.assertNotNull(secondUnmanagedDataDisk); String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri(); String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri(); Assertions.assertNotNull(createdVhdUri1); Assertions.assertNotNull(createdVhdUri2); computeManager.virtualMachines().deleteById(virtualMachine.id()); virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withUnmanagedDisks() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(1, unmanagedDataDisks.size()); firstUnmanagedDataDisk = null; for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) { firstUnmanagedDataDisk = unmanagedDisk; break; } Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri()); Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1)); virtualMachine .update() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .apply(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); } @Test public void canUpdateTagsOnVM() { VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); virtualMachine.update().withTag("test", "testValue").apply(); Assertions.assertEquals("testValue", virtualMachine.innerModel().tags().get("test")); Map<String, String> testTags = new HashMap<String, String>(); testTags.put("testTag", "testValue"); virtualMachine.update().withTags(testTags).apply(); Assertions.assertEquals(testTags.get("testTag"), virtualMachine.innerModel().tags().get("testTag")); } @Test public void canRunScriptOnVM() { VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .create(); List<String> installGit = new ArrayList<>(); installGit.add("sudo apt-get update"); installGit.add("sudo apt-get install -y git"); RunCommandResult runResult = virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>()); Assertions.assertNotNull(runResult); Assertions.assertNotNull(runResult.value()); Assertions.assertTrue(runResult.value().size() > 0); } @Test @DoNotRecord(skipInPlayback = true) public void canPerformSimulateEvictionOnSpotVirtualMachine() { VirtualMachine virtualMachine = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertTrue(virtualMachine.osDiskSize() > 0); Disk disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertNotNull(disk); Assertions.assertEquals(DiskState.ATTACHED, disk.innerModel().diskState()); virtualMachine.simulateEviction(); boolean deallocated = false; int pollIntervalInMinutes = 5; for (int i = 0; i < 30; i += pollIntervalInMinutes) { ResourceManagerUtils.sleep(Duration.ofMinutes(pollIntervalInMinutes)); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); if (virtualMachine.powerState() == PowerState.DEALLOCATED) { deallocated = true; break; } } Assertions.assertTrue(deallocated); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); Assertions.assertNotNull(virtualMachine); Assertions.assertNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertEquals(0, virtualMachine.osDiskSize()); disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertEquals(DiskState.RESERVED, disk.innerModel().diskState()); } @Test public void canForceDeleteVirtualMachine() { computeManager.virtualMachines() .define(vmName) .withRegion("eastus2euap") .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .create(); VirtualMachine virtualMachine = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(virtualMachine); Assertions.assertEquals(Region.fromName("eastus2euap"), virtualMachine.region()); String nicId = virtualMachine.primaryNetworkInterfaceId(); computeManager.virtualMachines().deleteById(virtualMachine.id(), true); try { virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException ex) { virtualMachine = null; Assertions.assertEquals(404, ex.getResponse().getStatusCode()); } Assertions.assertNull(virtualMachine); NetworkInterface nic = networkManager.networkInterfaces().getById(nicId); Assertions.assertNotNull(nic); } @Test public void canCreateVirtualMachineWithDeleteOption() throws Exception { Region region = Region.US_WEST3; final String publicIpDnsLabel = generateRandomResourceName("pip", 20); Network network = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("default", "10.0.0.0/24") .create(); VirtualMachine vm1 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel/*, DeleteOptions.DELETE*/) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withNewDataDisk(computeManager.disks() .define("datadisk2") .withRegion(region) .withExistingResourceGroup(rgName) .withData() .withSizeInGB(10)) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(DeleteOptions.DELETE, vm1.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(0).deleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(1).deleteOptions()); Assertions.assertEquals(vm1.id(), computeManager.virtualMachines().getById(vm1.id()).id()); computeManager.virtualMachines().deleteById(vm1.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(2, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); PublicIpAddress publicIpAddress = computeManager.networkManager().publicIpAddresses().listByResourceGroup(rgName).stream().findFirst().get(); computeManager.networkManager().publicIpAddresses().deleteById(publicIpAddress.id()); String secondaryNicName = generateRandomResourceName("nic", 10); Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable = this .networkManager .networkInterfaces() .define(secondaryNicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic(); VirtualMachine vm2 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable, DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); computeManager.virtualMachines().deleteById(vm2.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(1, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); secondaryNetworkInterfaceCreatable = this .networkManager .networkInterfaces() .define(secondaryNicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic(); VirtualMachine vm3 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withNewDataDisk(computeManager.disks() .define("datadisk2") .withRegion(region) .withExistingResourceGroup(rgName) .withData() .withSizeInGB(10)) .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(DeleteOptions.DETACH, vm3.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(0).deleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(1).deleteOptions()); computeManager.virtualMachines().deleteById(vm3.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(3, computeManager.disks().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(2, computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count()); } @Test public void canUpdateVirtualMachineWithDeleteOption() throws Exception { Region region = Region.US_WEST3; Network network = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("default", "10.0.0.0/24") .create(); VirtualMachine vm1 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); vm1.update() .withNewDataDisk(10) .apply(); computeManager.virtualMachines().deleteById(vm1.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(1, computeManager.disks().listByResourceGroup(rgName).stream().count()); Disk disk = computeManager.disks().listByResourceGroup(rgName).stream().findFirst().get(); computeManager.disks().deleteById(disk.id()); VirtualMachine vm2 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); vm2.update() .withNewDataDisk(10) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .apply(); computeManager.virtualMachines().deleteById(vm2.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(2, computeManager.disks().listByResourceGroup(rgName).stream().count()); } @Test public void canHibernateVirtualMachine() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion("eastus2euap") .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3) .enableHibernation() .create(); Assertions.assertTrue(vm.isHibernationEnabled()); vm.deallocate(true); InstanceViewStatus hibernationStatus = vm.instanceView().statuses().stream() .filter(status -> "HibernationState/Hibernated".equals(status.code())) .findFirst().orElse(null); Assertions.assertNotNull(hibernationStatus); vm.start(); vm.deallocate(); vm.update() .disableHibernation() .apply(); Assertions.assertFalse(vm.isHibernationEnabled()); } @Test public void canOperateVirtualMachine() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.redeploy(); vm.powerOff(true); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.STOPPED, vm.powerState()); vm.start(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.restart(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.deallocate(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.DEALLOCATED, vm.powerState()); } @Test public void canCreateVirtualMachineWithEphemeralOSDisk() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) .withEphemeralOSDisk() .withPlacement(DiffDiskPlacement.CACHE_DISK) .withNewDataDisk(1, 1, CachingTypes.READ_WRITE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertNull(vm.osDiskDiskEncryptionSetId()); Assertions.assertTrue(vm.osDiskSize() > 0); Assertions.assertEquals(vm.osDiskDeleteOptions(), DeleteOptions.DELETE); Assertions.assertEquals(vm.osDiskCachingType(), CachingTypes.READ_ONLY); Assertions.assertFalse(CoreUtils.isNullOrEmpty(vm.dataDisks())); Assertions.assertTrue(vm.isOSDiskEphemeral()); Assertions.assertNotNull(vm.osDiskId()); String osDiskId = vm.osDiskId(); vm.update() .withoutDataDisk(1) .withNewDataDisk(1, 2, CachingTypes.NONE) .withNewDataDisk(1) .apply(); Assertions.assertEquals(vm.dataDisks().size(), 2); vm.powerOff(); vm.start(); vm.refresh(); Assertions.assertEquals(osDiskId, vm.osDiskId()); Assertions.assertThrows(Exception.class, vm::deallocate); } @Test public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { final String vmssName = generateRandomResourceName("vmss", 10); Network network = this .networkManager .networks() .define("vmssvnet") .withRegion(region.name()) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().getByName(rgName); LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); VirtualMachineScaleSet flexibleVMSS = this.computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(rgName) .withFlexibleOrchestrationMode() .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_DS1_V2) .withExistingPrimaryNetworkSubnet(network, "subnet1") .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .withoutPrimaryInternalLoadBalancer() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withCapacity(1) .withUpgradeMode(UpgradeMode.AUTOMATIC) .create(); String regularVMName = generateRandomResourceName("vm", 10); final String pipDnsLabel = generateRandomResourceName("pip", 10); VirtualMachine regularVM = this.computeManager .virtualMachines() .define(regularVMName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(pipDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("jvuser2") .withSsh(sshPublicKey()) .withExistingVirtualMachineScaleSet(flexibleVMSS) .create(); flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.id(), regularVM.virtualMachineScaleSetId()); Assertions.assertEquals(2, flexibleVMSS.capacity()); regularVM.deallocate(); Assertions.assertEquals(regularVM.powerState(), PowerState.DEALLOCATED); this.computeManager .virtualMachines().deleteById(regularVM.id()); flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.capacity(), 1); final String storageAccountName = generateRandomResourceName("stg", 17); Assertions.assertThrows( ApiErrorException.class, () -> computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withLatestLinuxImage("Canonical", "UbuntuServer", "14.04.2-LTS") .withRootUsername("jvuser3") .withSsh(sshPublicKey()) .withUnmanagedDisks() /* UN-MANAGED OS and DATA DISKS */ .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withNewStorageAccount(storageAccountName) .withOSDiskCaching(CachingTypes.READ_WRITE) .withExistingVirtualMachineScaleSet(flexibleVMSS) .create() ); final String vmssName2 = generateRandomResourceName("vmss", 10); Network network2 = this .networkManager .networks() .define("vmssvnet2") .withRegion(region.name()) .withExistingResourceGroup(rgName) .withAddressSpace("192.168.0.0/28") .withSubnet("subnet2", "192.168.0.0/28") .create(); LoadBalancer publicLoadBalancer2 = createHttpLoadBalancers(region, resourceGroup, "2", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); VirtualMachineScaleSet uniformVMSS = this.computeManager .virtualMachineScaleSets() .define(vmssName2) .withRegion(region) .withNewResourceGroup(rgName) .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) .withExistingPrimaryNetworkSubnet(network2, "subnet2") .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer2) .withoutPrimaryInternalLoadBalancer() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser4") .withSsh(sshPublicKey()) .withCapacity(1) .create(); Assertions.assertTrue(uniformVMSS.virtualMachines().list().stream().allMatch(v -> v.instanceId() != null)); String regularVMName2 = generateRandomResourceName("vm", 10); Assertions.assertThrows( ApiErrorException.class, () -> this.computeManager .virtualMachines() .define(regularVMName2) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("jvuser5") .withSsh(sshPublicKey()) .withExistingVirtualMachineScaleSet(uniformVMSS) .create() ); } @Test @DoNotRecord(skipInPlayback = true) public void canSwapOSDiskWithManagedDisk() { String storageAccountName = generateRandomResourceName("sa", 15); StorageAccount storageAccount = this.storageManager .storageAccounts() .define(storageAccountName) .withRegion(region) .withNewResourceGroup(rgName) .create(); String vm1Name = generateRandomResourceName("vm", 15); VirtualMachine vm1 = this.computeManager .virtualMachines() .define(vm1Name) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/24") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withNewDataDisk(10, 1, CachingTypes.READ_WRITE) .withOSDiskDeleteOptions(DeleteOptions.DETACH) .withExistingStorageAccount(storageAccount) .create(); Disk vm1OSDisk = this.computeManager.disks().getById(vm1.osDiskId()); Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_KEY, vm1OSDisk.encryption().type()); String vaultName = generateRandomResourceName("vault", 15); Vault vault = this.keyVaultManager .vaults() .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowKeyPermissions(KeyPermissions.CREATE) .attach() .create(); String keyName = generateRandomResourceName("key", 15); Key key = vault.keys() .define(keyName) .withKeyTypeToCreate(KeyType.RSA) .withKeySize(4096) .create(); String desName = generateRandomResourceName("des", 15); DiskEncryptionSet des = this.computeManager.diskEncryptionSets() .define(desName) .withRegion(region) .withExistingResourceGroup(rgName) .withEncryptionType(DiskEncryptionSetType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY) .withExistingKeyVault(vault.id()) .withExistingKey(key.id()) .withSystemAssignedManagedServiceIdentity() .create(); vault.update() .defineAccessPolicy() .forObjectId(des.systemAssignedManagedServiceIdentityPrincipalId()) .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.UNWRAP_KEY, KeyPermissions.WRAP_KEY) .attach() .withPurgeProtectionEnabled() .apply(); String vm2Name = generateRandomResourceName("vm", 15); VirtualMachine vm2 = this.computeManager.virtualMachines() .define(vm2Name) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/24") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withOSDiskDiskEncryptionSet(des.id()) .withOSDiskDeleteOptions(DeleteOptions.DETACH) .create(); String vm2OSDiskId = vm2.osDiskId(); this.computeManager.virtualMachines().deleteById(vm2.id()); Disk vm2OSDisk = this.computeManager.disks().getById(vm2OSDiskId); Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY, vm2OSDisk.encryption().type()); vm1.deallocate(); vm1.update() .withOSDisk(vm2OSDiskId) .apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm2OSDiskId); Assertions.assertTrue(des.id().equalsIgnoreCase(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet().id())); vm1.deallocate(); vm1.update() .withOSDisk(vm1OSDisk) .apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm1OSDisk.id()); Assertions.assertNull(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet()); } @Test public void canCRUDTrustedLaunchVM() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_20_04_LTS_GEN2) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withTrustedLaunch() .withSecureBoot() .withVTpm() .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertEquals(SecurityTypes.TRUSTED_LAUNCH, vm.securityType()); Assertions.assertTrue(vm.isSecureBootEnabled()); Assertions.assertTrue(vm.isVTpmEnabled()); vm.update() .withoutSecureBoot() .withoutVTpm() .applyAsync() .flatMap(VirtualMachine::restartAsync) .block(); ResourceManagerUtils.sleep(Duration.ofMinutes(1)); vm = computeManager.virtualMachines().getById(vm.id()); Assertions.assertEquals(SecurityTypes.TRUSTED_LAUNCH, vm.securityType()); Assertions.assertFalse(vm.isSecureBootEnabled()); Assertions.assertFalse(vm.isVTpmEnabled()); computeManager.virtualMachines().deleteById(vm.id()); } @Test private CreatablesInfo prepareCreatableVirtualMachines( Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) { Creatable<ResourceGroup> resourceGroupCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); Creatable<StorageAccount> storageAccountCreatable = storageManager .storageAccounts() .define(generateRandomResourceName("stg", 20)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); List<String> networkCreatableKeys = new ArrayList<>(); List<String> publicIpCreatableKeys = new ArrayList<>(); List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>(); for (int i = 0; i < vmCount; i++) { Creatable<Network> networkCreatable = networkManager .networks() .define(String.format("%s-%d", networkNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withAddressSpace("10.0.0.0/28"); networkCreatableKeys.add(networkCreatable.key()); Creatable<PublicIpAddress> publicIPAddressCreatable = networkManager .publicIpAddresses() .define(String.format("%s-%d", publicIpNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); publicIpCreatableKeys.add(publicIPAddressCreatable.key()); Creatable<VirtualMachine> virtualMachineCreatable = computeManager .virtualMachines() .define(String.format("%s-%d", vmNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withNewPrimaryNetwork(networkCreatable) .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("tirekicker") .withSsh(sshPublicKey()) .withUnmanagedDisks() .withNewStorageAccount(storageAccountCreatable); virtualMachineCreatables.add(virtualMachineCreatable); } CreatablesInfo creatablesInfo = new CreatablesInfo(); creatablesInfo.virtualMachineCreatables = virtualMachineCreatables; creatablesInfo.networkCreatableKeys = networkCreatableKeys; creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys; return creatablesInfo; } class CreatablesInfo { private List<Creatable<VirtualMachine>> virtualMachineCreatables; List<String> networkCreatableKeys; List<String> publicIpCreatableKeys; } }
Yeah, powerOff() isn't enough for adding a new nic.
public void canUpdateDeleteOptions() { String networkName = generateRandomResourceName("network", 15); String nicName = generateRandomResourceName("nic", 15); String nicName2 = generateRandomResourceName("nic", 15); Network network = this .networkManager .networks() .define(networkName) .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.1.0/24") .withSubnet("subnet1", "10.0.1.0/28") .withSubnet("subnet2", "10.0.1.16/28") .create(); VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet1") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_20_04_LTS_GEN2) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withNewDataDisk(10, 1, new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DELETE)) .withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2) .withNewSecondaryNetworkInterface(this .networkManager .networkInterfaces() .define(nicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet1") .withPrimaryPrivateIPAddressDynamic(), DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertEquals(DeleteOptions.DELETE, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); vm.update() .withOsDiskDeleteOptions(DeleteOptions.DETACH) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DETACH) .withDataDiskDeleteOptions(1, DeleteOptions.DETACH) .withNewDataDisk(1) .apply(); Assertions.assertEquals(DeleteOptions.DETACH, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.networkInterfaceIds().stream() .filter(nicId -> !nicId.equals(vm.primaryNetworkInterfaceId())).allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DETACH.equals(disk.deleteOptions()))); NetworkInterface secondaryNic2 = this .networkManager .networkInterfaces() .define(nicName2) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet2") .withPrimaryPrivateIPAddressDynamic() .create(); vm.powerOff(); vm.deallocate(); vm.update() .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withDataDisksDeleteOptions(DeleteOptions.DELETE) .withNewDataDisk(1) .withSecondaryNetworkInterfacesDeleteOptions(DeleteOptions.DELETE) .withExistingSecondaryNetworkInterface(secondaryNic2) .apply(); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.networkInterfaceIds().stream().allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); }
vm.deallocate();
public void canUpdateDeleteOptions() { String networkName = generateRandomResourceName("network", 15); String nicName = generateRandomResourceName("nic", 15); String nicName2 = generateRandomResourceName("nic", 15); Network network = this .networkManager .networks() .define(networkName) .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.1.0/24") .withSubnet("subnet1", "10.0.1.0/28") .withSubnet("subnet2", "10.0.1.16/28") .create(); VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet1") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_20_04_LTS_GEN2) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withNewDataDisk(10, 1, new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DELETE)) .withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2) .withNewSecondaryNetworkInterface(this .networkManager .networkInterfaces() .define(nicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet1") .withPrimaryPrivateIPAddressDynamic(), DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertEquals(DeleteOptions.DELETE, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); vm.update() .withOsDiskDeleteOptions(DeleteOptions.DETACH) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DETACH) .withDataDisksDeleteOptions(DeleteOptions.DETACH, 1) .apply(); Assertions.assertEquals(DeleteOptions.DETACH, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.networkInterfaceIds().stream() .filter(nicId -> !nicId.equals(vm.primaryNetworkInterfaceId())).allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DETACH.equals(disk.deleteOptions()))); NetworkInterface secondaryNic2 = this .networkManager .networkInterfaces() .define(nicName2) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("subnet2") .withPrimaryPrivateIPAddressDynamic() .create(); vm.powerOff(); vm.deallocate(); vm.update() .withNewDataDisk(1, 2, new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DETACH)) .withExistingSecondaryNetworkInterface(secondaryNic2) .apply(); vm.update() .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withDataDisksDeleteOptions(DeleteOptions.DELETE, new ArrayList<>(vm.dataDisks().keySet()).toArray(new Integer[0])) .withNetworkInterfacesDeleteOptions( DeleteOptions.DELETE, vm.networkInterfaceIds().stream().filter(nic -> !nic.equals(vm.primaryNetworkInterfaceId())).toArray(String[]::new)) .apply(); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); Assertions.assertTrue(vm.networkInterfaceIds().stream().allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); }
class VirtualMachineOperationsTests extends ComputeManagementTest { private String rgName = ""; private String rgName2 = ""; private final Region region = Region.US_EAST; private final Region regionProxPlacementGroup = Region.US_WEST; private final Region regionProxPlacementGroup2 = Region.US_EAST; private final String vmName = "javavm"; private final String proxGroupName = "testproxgroup1"; private final String proxGroupName2 = "testproxgroup2"; private final String availabilitySetName = "availset1"; private final String availabilitySetName2 = "availset2"; private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); rgName2 = generateRandomResourceName("javacsmrg2", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName != null) { resourceManager.resourceGroups().beginDeleteByName(rgName); } } @Test public void canCreateVirtualMachineWithNetworking() throws Exception { NetworkSecurityGroup nsg = this .networkManager .networkSecurityGroups() .define("nsg") .withRegion(region) .withNewResourceGroup(rgName) .defineRule("rule1") .allowInbound() .fromAnyAddress() .fromPort(80) .toAnyAddress() .toPort(80) .withProtocol(SecurityRuleProtocol.TCP) .attach() .create(); Creatable<Network> networkDefinition = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .defineSubnet("subnet1") .withAddressPrefix("10.0.0.0/29") .withExistingNetworkSecurityGroup(nsg) .attach(); VirtualMachine vm = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork(networkDefinition) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .create(); NetworkInterface primaryNic = vm.getPrimaryNetworkInterface(); Assertions.assertNotNull(primaryNic); NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration(); Assertions.assertNotNull(primaryIpConfig); Assertions.assertNotNull(primaryIpConfig.networkId()); Network network = primaryIpConfig.getNetwork(); Assertions.assertNotNull(primaryIpConfig.subnetName()); Subnet subnet = network.subnets().get(primaryIpConfig.subnetName()); Assertions.assertNotNull(subnet); nsg = subnet.getNetworkSecurityGroup(); Assertions.assertNotNull(nsg); Assertions.assertEquals("nsg", nsg.name()); Assertions.assertEquals(1, nsg.securityRules().size()); nsg = primaryIpConfig.getNetworkSecurityGroup(); Assertions.assertEquals("nsg", nsg.name()); } @Test public void canCreateVirtualMachine() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertNotNull(foundVM.timeCreated()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotCreateVirtualMachineSyncPoll() throws Exception { final String mySqlInstallScript = "https: final String installCommand = "bash install_mysql_server_5.6.sh Abc.123x("; Assertions.assertThrows(IllegalStateException.class, () -> { Accepted<VirtualMachine> acceptedVirtualMachine = this.computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .defineNewExtension("CustomScriptForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("CustomScriptForLinux") .withVersion("1.4") .withMinorVersionAutoUpgrade() .withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript)) .withPublicSetting("commandToExecute", installCommand) .attach() .beginCreate(); }); boolean dependentResourceCreated = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName); Assertions.assertFalse(dependentResourceCreated); rgName = null; } @Test public void canCreateVirtualMachineSyncPoll() throws Exception { final long defaultDelayInMillis = 10 * 1000; Accepted<VirtualMachine> acceptedVirtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .beginCreate(); VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue(); Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState()); LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus(); long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills)); PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult(); Assertions.assertEquals("Succeeded", virtualMachine.provisioningState()); Accepted<Void> acceptedDelete = computeManager.virtualMachines() .beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name()); pollStatus = acceptedDelete.getActivationResponse().getStatus(); delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills)); PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : (int) pollResponse.getRetryAfter().toMillis(); } boolean deleted = false; try { computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException e) { if (e.getResponse().getStatusCode() == 404 && ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) { deleted = true; } } Assertions.assertTrue(deleted); } @Test public void canCreateUpdatePriorityAndPrice() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withMaxPrice(1000.0) .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice()); Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy()); try { foundVM.update().withMaxPrice(1500.0).apply(); Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice()); Assertions.fail(); } catch (ManagementException e) { } foundVM.deallocate(); foundVM.update().withMaxPrice(2000.0).apply(); foundVM.start(); Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority()); try { foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority()); Assertions.fail(); } catch (ManagementException e) { } computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); AvailabilitySet setCreated2 = computeManager .availabilitySets() .define(availabilitySetName2) .withRegion(regionProxPlacementGroup2) .withNewResourceGroup(rgName2) .withNewProximityPlacementGroup(proxGroupName2, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName2, setCreated2.name()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); try { VirtualMachine updatedVm = foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply(); } catch (ManagementException clEx) { Assertions .assertTrue( clEx .getMessage() .contains( "Updating proximity placement group of VM javavm is not allowed while the VM is running." + " Please stop/deallocate the VM and retry the operation.")); } computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply(); Assertions.assertNotNull(updatedVm.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0))); computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys; List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys; CreatedResources<VirtualMachine> createdVirtualMachines = computeManager.virtualMachines().create(virtualMachineCreatables); Assertions.assertTrue(createdVirtualMachines.size() == count); Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } for (VirtualMachine virtualMachine : createdVirtualMachines.values()) { Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } for (String networkCreatableKey : networkCreatableKeys) { Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey); Assertions.assertNotNull(createdNetwork); Assertions.assertTrue(networkNames.contains(createdNetwork.name())); } Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } for (String publicIpCreatableKey : publicIpCreatableKeys) { PublicIpAddress createdPublicIpAddress = (PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey); Assertions.assertNotNull(createdPublicIpAddress); Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name())); } } @Test public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; final Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } final Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } final Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } final CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); final AtomicInteger resourceCount = new AtomicInteger(0); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; computeManager .virtualMachines() .createAsync(virtualMachineCreatables) .map( createdResource -> { if (createdResource instanceof Resource) { Resource resource = (Resource) createdResource; System.out.println("Created: " + resource.id()); if (resource instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine) resource; Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } else if (resource instanceof Network) { Network network = (Network) resource; Assertions.assertTrue(networkNames.contains(network.name())); Assertions.assertNotNull(network.id()); } else if (resource instanceof PublicIpAddress) { PublicIpAddress publicIPAddress = (PublicIpAddress) resource; Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name())); Assertions.assertNotNull(publicIPAddress.id()); } } resourceCount.incrementAndGet(); return createdResource; }) .blockLast(); networkNames.forEach(name -> { Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name)); }); publicIPAddressNames.forEach(name -> { Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name)); }); Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, resourceCount.get()); } @Test public void canSetStorageAccountForUnmanagedDisk() { final String storageName = generateRandomResourceName("st", 14); StorageAccount storageAccount = storageManager .storageAccounts() .define(storageName) .withRegion(region) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.PREMIUM_LRS) .create(); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withUnmanagedDisks() .defineUnmanagedDataDisk("disk1") .withNewVhd(100) .withLun(2) .storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .attach() .defineUnmanagedDataDisk("disk2") .withNewVhd(100) .withLun(3) .storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .attach() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .create(); Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2); Assertions.assertNotNull(firstUnmanagedDataDisk); VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3); Assertions.assertNotNull(secondUnmanagedDataDisk); String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri(); String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri(); Assertions.assertNotNull(createdVhdUri1); Assertions.assertNotNull(createdVhdUri2); computeManager.virtualMachines().deleteById(virtualMachine.id()); virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withUnmanagedDisks() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(1, unmanagedDataDisks.size()); firstUnmanagedDataDisk = null; for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) { firstUnmanagedDataDisk = unmanagedDisk; break; } Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri()); Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1)); virtualMachine .update() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .apply(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); } @Test public void canUpdateTagsOnVM() { VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); virtualMachine.update().withTag("test", "testValue").apply(); Assertions.assertEquals("testValue", virtualMachine.innerModel().tags().get("test")); Map<String, String> testTags = new HashMap<String, String>(); testTags.put("testTag", "testValue"); virtualMachine.update().withTags(testTags).apply(); Assertions.assertEquals(testTags.get("testTag"), virtualMachine.innerModel().tags().get("testTag")); } @Test public void canRunScriptOnVM() { VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .create(); List<String> installGit = new ArrayList<>(); installGit.add("sudo apt-get update"); installGit.add("sudo apt-get install -y git"); RunCommandResult runResult = virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>()); Assertions.assertNotNull(runResult); Assertions.assertNotNull(runResult.value()); Assertions.assertTrue(runResult.value().size() > 0); } @Test @DoNotRecord(skipInPlayback = true) public void canPerformSimulateEvictionOnSpotVirtualMachine() { VirtualMachine virtualMachine = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertTrue(virtualMachine.osDiskSize() > 0); Disk disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertNotNull(disk); Assertions.assertEquals(DiskState.ATTACHED, disk.innerModel().diskState()); virtualMachine.simulateEviction(); boolean deallocated = false; int pollIntervalInMinutes = 5; for (int i = 0; i < 30; i += pollIntervalInMinutes) { ResourceManagerUtils.sleep(Duration.ofMinutes(pollIntervalInMinutes)); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); if (virtualMachine.powerState() == PowerState.DEALLOCATED) { deallocated = true; break; } } Assertions.assertTrue(deallocated); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); Assertions.assertNotNull(virtualMachine); Assertions.assertNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertEquals(0, virtualMachine.osDiskSize()); disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertEquals(DiskState.RESERVED, disk.innerModel().diskState()); } @Test public void canForceDeleteVirtualMachine() { computeManager.virtualMachines() .define(vmName) .withRegion("eastus2euap") .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .create(); VirtualMachine virtualMachine = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(virtualMachine); Assertions.assertEquals(Region.fromName("eastus2euap"), virtualMachine.region()); String nicId = virtualMachine.primaryNetworkInterfaceId(); computeManager.virtualMachines().deleteById(virtualMachine.id(), true); try { virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException ex) { virtualMachine = null; Assertions.assertEquals(404, ex.getResponse().getStatusCode()); } Assertions.assertNull(virtualMachine); NetworkInterface nic = networkManager.networkInterfaces().getById(nicId); Assertions.assertNotNull(nic); } @Test public void canCreateVirtualMachineWithDeleteOption() throws Exception { Region region = Region.US_WEST3; final String publicIpDnsLabel = generateRandomResourceName("pip", 20); Network network = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("default", "10.0.0.0/24") .create(); VirtualMachine vm1 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel/*, DeleteOptions.DELETE*/) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withNewDataDisk(computeManager.disks() .define("datadisk2") .withRegion(region) .withExistingResourceGroup(rgName) .withData() .withSizeInGB(10)) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(DeleteOptions.DELETE, vm1.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(0).deleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(1).deleteOptions()); Assertions.assertEquals(vm1.id(), computeManager.virtualMachines().getById(vm1.id()).id()); computeManager.virtualMachines().deleteById(vm1.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(2, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); PublicIpAddress publicIpAddress = computeManager.networkManager().publicIpAddresses().listByResourceGroup(rgName).stream().findFirst().get(); computeManager.networkManager().publicIpAddresses().deleteById(publicIpAddress.id()); String secondaryNicName = generateRandomResourceName("nic", 10); Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable = this .networkManager .networkInterfaces() .define(secondaryNicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic(); VirtualMachine vm2 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable, DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); computeManager.virtualMachines().deleteById(vm2.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(1, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); secondaryNetworkInterfaceCreatable = this .networkManager .networkInterfaces() .define(secondaryNicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic(); VirtualMachine vm3 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withNewDataDisk(computeManager.disks() .define("datadisk2") .withRegion(region) .withExistingResourceGroup(rgName) .withData() .withSizeInGB(10)) .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(DeleteOptions.DETACH, vm3.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(0).deleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(1).deleteOptions()); computeManager.virtualMachines().deleteById(vm3.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(3, computeManager.disks().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(2, computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count()); } @Test public void canUpdateVirtualMachineWithDeleteOption() throws Exception { Region region = Region.US_WEST3; Network network = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("default", "10.0.0.0/24") .create(); VirtualMachine vm1 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); vm1.update() .withNewDataDisk(10) .apply(); computeManager.virtualMachines().deleteById(vm1.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(1, computeManager.disks().listByResourceGroup(rgName).stream().count()); Disk disk = computeManager.disks().listByResourceGroup(rgName).stream().findFirst().get(); computeManager.disks().deleteById(disk.id()); VirtualMachine vm2 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); vm2.update() .withNewDataDisk(10) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .apply(); computeManager.virtualMachines().deleteById(vm2.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(2, computeManager.disks().listByResourceGroup(rgName).stream().count()); } @Test public void canHibernateVirtualMachine() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion("eastus2euap") .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3) .enableHibernation() .create(); Assertions.assertTrue(vm.isHibernationEnabled()); vm.deallocate(true); InstanceViewStatus hibernationStatus = vm.instanceView().statuses().stream() .filter(status -> "HibernationState/Hibernated".equals(status.code())) .findFirst().orElse(null); Assertions.assertNotNull(hibernationStatus); vm.start(); vm.deallocate(); vm.update() .disableHibernation() .apply(); Assertions.assertFalse(vm.isHibernationEnabled()); } @Test public void canOperateVirtualMachine() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.redeploy(); vm.powerOff(true); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.STOPPED, vm.powerState()); vm.start(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.restart(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.deallocate(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.DEALLOCATED, vm.powerState()); } @Test public void canCreateVirtualMachineWithEphemeralOSDisk() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) .withEphemeralOSDisk() .withPlacement(DiffDiskPlacement.CACHE_DISK) .withNewDataDisk(1, 1, CachingTypes.READ_WRITE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertNull(vm.osDiskDiskEncryptionSetId()); Assertions.assertTrue(vm.osDiskSize() > 0); Assertions.assertEquals(vm.osDiskDeleteOptions(), DeleteOptions.DELETE); Assertions.assertEquals(vm.osDiskCachingType(), CachingTypes.READ_ONLY); Assertions.assertFalse(CoreUtils.isNullOrEmpty(vm.dataDisks())); Assertions.assertTrue(vm.isOSDiskEphemeral()); Assertions.assertNotNull(vm.osDiskId()); String osDiskId = vm.osDiskId(); vm.update() .withoutDataDisk(1) .withNewDataDisk(1, 2, CachingTypes.NONE) .withNewDataDisk(1) .apply(); Assertions.assertEquals(vm.dataDisks().size(), 2); vm.powerOff(); vm.start(); vm.refresh(); Assertions.assertEquals(osDiskId, vm.osDiskId()); Assertions.assertThrows(Exception.class, vm::deallocate); } @Test public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { final String vmssName = generateRandomResourceName("vmss", 10); Network network = this .networkManager .networks() .define("vmssvnet") .withRegion(region.name()) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().getByName(rgName); LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); VirtualMachineScaleSet flexibleVMSS = this.computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(rgName) .withFlexibleOrchestrationMode() .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_DS1_V2) .withExistingPrimaryNetworkSubnet(network, "subnet1") .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .withoutPrimaryInternalLoadBalancer() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withCapacity(1) .withUpgradeMode(UpgradeMode.AUTOMATIC) .create(); String regularVMName = generateRandomResourceName("vm", 10); final String pipDnsLabel = generateRandomResourceName("pip", 10); VirtualMachine regularVM = this.computeManager .virtualMachines() .define(regularVMName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(pipDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("jvuser2") .withSsh(sshPublicKey()) .withExistingVirtualMachineScaleSet(flexibleVMSS) .create(); flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.id(), regularVM.virtualMachineScaleSetId()); Assertions.assertEquals(2, flexibleVMSS.capacity()); regularVM.deallocate(); Assertions.assertEquals(regularVM.powerState(), PowerState.DEALLOCATED); this.computeManager .virtualMachines().deleteById(regularVM.id()); flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.capacity(), 1); final String storageAccountName = generateRandomResourceName("stg", 17); Assertions.assertThrows( ApiErrorException.class, () -> computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withLatestLinuxImage("Canonical", "UbuntuServer", "14.04.2-LTS") .withRootUsername("jvuser3") .withSsh(sshPublicKey()) .withUnmanagedDisks() /* UN-MANAGED OS and DATA DISKS */ .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withNewStorageAccount(storageAccountName) .withOSDiskCaching(CachingTypes.READ_WRITE) .withExistingVirtualMachineScaleSet(flexibleVMSS) .create() ); final String vmssName2 = generateRandomResourceName("vmss", 10); Network network2 = this .networkManager .networks() .define("vmssvnet2") .withRegion(region.name()) .withExistingResourceGroup(rgName) .withAddressSpace("192.168.0.0/28") .withSubnet("subnet2", "192.168.0.0/28") .create(); LoadBalancer publicLoadBalancer2 = createHttpLoadBalancers(region, resourceGroup, "2", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); VirtualMachineScaleSet uniformVMSS = this.computeManager .virtualMachineScaleSets() .define(vmssName2) .withRegion(region) .withNewResourceGroup(rgName) .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) .withExistingPrimaryNetworkSubnet(network2, "subnet2") .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer2) .withoutPrimaryInternalLoadBalancer() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser4") .withSsh(sshPublicKey()) .withCapacity(1) .create(); Assertions.assertTrue(uniformVMSS.virtualMachines().list().stream().allMatch(v -> v.instanceId() != null)); String regularVMName2 = generateRandomResourceName("vm", 10); Assertions.assertThrows( ApiErrorException.class, () -> this.computeManager .virtualMachines() .define(regularVMName2) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("jvuser5") .withSsh(sshPublicKey()) .withExistingVirtualMachineScaleSet(uniformVMSS) .create() ); } @Test @DoNotRecord(skipInPlayback = true) public void canSwapOSDiskWithManagedDisk() { String storageAccountName = generateRandomResourceName("sa", 15); StorageAccount storageAccount = this.storageManager .storageAccounts() .define(storageAccountName) .withRegion(region) .withNewResourceGroup(rgName) .create(); String vm1Name = generateRandomResourceName("vm", 15); VirtualMachine vm1 = this.computeManager .virtualMachines() .define(vm1Name) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/24") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withNewDataDisk(10, 1, CachingTypes.READ_WRITE) .withOSDiskDeleteOptions(DeleteOptions.DETACH) .withExistingStorageAccount(storageAccount) .create(); Disk vm1OSDisk = this.computeManager.disks().getById(vm1.osDiskId()); Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_KEY, vm1OSDisk.encryption().type()); String vaultName = generateRandomResourceName("vault", 15); Vault vault = this.keyVaultManager .vaults() .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowKeyPermissions(KeyPermissions.CREATE) .attach() .create(); String keyName = generateRandomResourceName("key", 15); Key key = vault.keys() .define(keyName) .withKeyTypeToCreate(KeyType.RSA) .withKeySize(4096) .create(); String desName = generateRandomResourceName("des", 15); DiskEncryptionSet des = this.computeManager.diskEncryptionSets() .define(desName) .withRegion(region) .withExistingResourceGroup(rgName) .withEncryptionType(DiskEncryptionSetType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY) .withExistingKeyVault(vault.id()) .withExistingKey(key.id()) .withSystemAssignedManagedServiceIdentity() .create(); vault.update() .defineAccessPolicy() .forObjectId(des.systemAssignedManagedServiceIdentityPrincipalId()) .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.UNWRAP_KEY, KeyPermissions.WRAP_KEY) .attach() .withPurgeProtectionEnabled() .apply(); String vm2Name = generateRandomResourceName("vm", 15); VirtualMachine vm2 = this.computeManager.virtualMachines() .define(vm2Name) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/24") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withOSDiskDiskEncryptionSet(des.id()) .withOSDiskDeleteOptions(DeleteOptions.DETACH) .create(); String vm2OSDiskId = vm2.osDiskId(); this.computeManager.virtualMachines().deleteById(vm2.id()); Disk vm2OSDisk = this.computeManager.disks().getById(vm2OSDiskId); Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY, vm2OSDisk.encryption().type()); vm1.deallocate(); vm1.update() .withOSDisk(vm2OSDiskId) .apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm2OSDiskId); Assertions.assertTrue(des.id().equalsIgnoreCase(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet().id())); vm1.deallocate(); vm1.update() .withOSDisk(vm1OSDisk) .apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm1OSDisk.id()); Assertions.assertNull(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet()); } @Test public void canCRUDTrustedLaunchVM() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_20_04_LTS_GEN2) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withTrustedLaunch() .withSecureBoot() .withVTpm() .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertEquals(SecurityTypes.TRUSTED_LAUNCH, vm.securityType()); Assertions.assertTrue(vm.isSecureBootEnabled()); Assertions.assertTrue(vm.isVTpmEnabled()); vm.update() .withoutSecureBoot() .withoutVTpm() .applyAsync() .flatMap(VirtualMachine::restartAsync) .block(); ResourceManagerUtils.sleep(Duration.ofMinutes(1)); vm = computeManager.virtualMachines().getById(vm.id()); Assertions.assertEquals(SecurityTypes.TRUSTED_LAUNCH, vm.securityType()); Assertions.assertFalse(vm.isSecureBootEnabled()); Assertions.assertFalse(vm.isVTpmEnabled()); computeManager.virtualMachines().deleteById(vm.id()); } @Test private CreatablesInfo prepareCreatableVirtualMachines( Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) { Creatable<ResourceGroup> resourceGroupCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); Creatable<StorageAccount> storageAccountCreatable = storageManager .storageAccounts() .define(generateRandomResourceName("stg", 20)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); List<String> networkCreatableKeys = new ArrayList<>(); List<String> publicIpCreatableKeys = new ArrayList<>(); List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>(); for (int i = 0; i < vmCount; i++) { Creatable<Network> networkCreatable = networkManager .networks() .define(String.format("%s-%d", networkNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withAddressSpace("10.0.0.0/28"); networkCreatableKeys.add(networkCreatable.key()); Creatable<PublicIpAddress> publicIPAddressCreatable = networkManager .publicIpAddresses() .define(String.format("%s-%d", publicIpNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); publicIpCreatableKeys.add(publicIPAddressCreatable.key()); Creatable<VirtualMachine> virtualMachineCreatable = computeManager .virtualMachines() .define(String.format("%s-%d", vmNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withNewPrimaryNetwork(networkCreatable) .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("tirekicker") .withSsh(sshPublicKey()) .withUnmanagedDisks() .withNewStorageAccount(storageAccountCreatable); virtualMachineCreatables.add(virtualMachineCreatable); } CreatablesInfo creatablesInfo = new CreatablesInfo(); creatablesInfo.virtualMachineCreatables = virtualMachineCreatables; creatablesInfo.networkCreatableKeys = networkCreatableKeys; creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys; return creatablesInfo; } class CreatablesInfo { private List<Creatable<VirtualMachine>> virtualMachineCreatables; List<String> networkCreatableKeys; List<String> publicIpCreatableKeys; } }
class VirtualMachineOperationsTests extends ComputeManagementTest { private String rgName = ""; private String rgName2 = ""; private final Region region = Region.US_EAST; private final Region regionProxPlacementGroup = Region.US_WEST; private final Region regionProxPlacementGroup2 = Region.US_EAST; private final String vmName = "javavm"; private final String proxGroupName = "testproxgroup1"; private final String proxGroupName2 = "testproxgroup2"; private final String availabilitySetName = "availset1"; private final String availabilitySetName2 = "availset2"; private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); rgName2 = generateRandomResourceName("javacsmrg2", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName != null) { resourceManager.resourceGroups().beginDeleteByName(rgName); } } @Test public void canCreateVirtualMachineWithNetworking() throws Exception { NetworkSecurityGroup nsg = this .networkManager .networkSecurityGroups() .define("nsg") .withRegion(region) .withNewResourceGroup(rgName) .defineRule("rule1") .allowInbound() .fromAnyAddress() .fromPort(80) .toAnyAddress() .toPort(80) .withProtocol(SecurityRuleProtocol.TCP) .attach() .create(); Creatable<Network> networkDefinition = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .defineSubnet("subnet1") .withAddressPrefix("10.0.0.0/29") .withExistingNetworkSecurityGroup(nsg) .attach(); VirtualMachine vm = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork(networkDefinition) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .create(); NetworkInterface primaryNic = vm.getPrimaryNetworkInterface(); Assertions.assertNotNull(primaryNic); NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration(); Assertions.assertNotNull(primaryIpConfig); Assertions.assertNotNull(primaryIpConfig.networkId()); Network network = primaryIpConfig.getNetwork(); Assertions.assertNotNull(primaryIpConfig.subnetName()); Subnet subnet = network.subnets().get(primaryIpConfig.subnetName()); Assertions.assertNotNull(subnet); nsg = subnet.getNetworkSecurityGroup(); Assertions.assertNotNull(nsg); Assertions.assertEquals("nsg", nsg.name()); Assertions.assertEquals(1, nsg.securityRules().size()); nsg = primaryIpConfig.getNetworkSecurityGroup(); Assertions.assertEquals("nsg", nsg.name()); } @Test public void canCreateVirtualMachine() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertNotNull(foundVM.timeCreated()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotCreateVirtualMachineSyncPoll() throws Exception { final String mySqlInstallScript = "https: final String installCommand = "bash install_mysql_server_5.6.sh Abc.123x("; Assertions.assertThrows(IllegalStateException.class, () -> { Accepted<VirtualMachine> acceptedVirtualMachine = this.computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .defineNewExtension("CustomScriptForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("CustomScriptForLinux") .withVersion("1.4") .withMinorVersionAutoUpgrade() .withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript)) .withPublicSetting("commandToExecute", installCommand) .attach() .beginCreate(); }); boolean dependentResourceCreated = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName); Assertions.assertFalse(dependentResourceCreated); rgName = null; } @Test public void canCreateVirtualMachineSyncPoll() throws Exception { final long defaultDelayInMillis = 10 * 1000; Accepted<VirtualMachine> acceptedVirtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .beginCreate(); VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue(); Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState()); LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus(); long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills)); PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult(); Assertions.assertEquals("Succeeded", virtualMachine.provisioningState()); Accepted<Void> acceptedDelete = computeManager.virtualMachines() .beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name()); pollStatus = acceptedDelete.getActivationResponse().getStatus(); delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills)); PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : (int) pollResponse.getRetryAfter().toMillis(); } boolean deleted = false; try { computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException e) { if (e.getResponse().getStatusCode() == 404 && ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) { deleted = true; } } Assertions.assertTrue(deleted); } @Test public void canCreateUpdatePriorityAndPrice() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withMaxPrice(1000.0) .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice()); Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy()); try { foundVM.update().withMaxPrice(1500.0).apply(); Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice()); Assertions.fail(); } catch (ManagementException e) { } foundVM.deallocate(); foundVM.update().withMaxPrice(2000.0).apply(); foundVM.start(); Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority()); try { foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority()); Assertions.fail(); } catch (ManagementException e) { } computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); AvailabilitySet setCreated2 = computeManager .availabilitySets() .define(availabilitySetName2) .withRegion(regionProxPlacementGroup2) .withNewResourceGroup(rgName2) .withNewProximityPlacementGroup(proxGroupName2, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName2, setCreated2.name()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); try { VirtualMachine updatedVm = foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply(); } catch (ManagementException clEx) { Assertions .assertTrue( clEx .getMessage() .contains( "Updating proximity placement group of VM javavm is not allowed while the VM is running." + " Please stop/deallocate the VM and retry the operation.")); } computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply(); Assertions.assertNotNull(updatedVm.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0))); computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys; List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys; CreatedResources<VirtualMachine> createdVirtualMachines = computeManager.virtualMachines().create(virtualMachineCreatables); Assertions.assertTrue(createdVirtualMachines.size() == count); Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } for (VirtualMachine virtualMachine : createdVirtualMachines.values()) { Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } for (String networkCreatableKey : networkCreatableKeys) { Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey); Assertions.assertNotNull(createdNetwork); Assertions.assertTrue(networkNames.contains(createdNetwork.name())); } Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } for (String publicIpCreatableKey : publicIpCreatableKeys) { PublicIpAddress createdPublicIpAddress = (PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey); Assertions.assertNotNull(createdPublicIpAddress); Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name())); } } @Test public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; final Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } final Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } final Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } final CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); final AtomicInteger resourceCount = new AtomicInteger(0); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; computeManager .virtualMachines() .createAsync(virtualMachineCreatables) .map( createdResource -> { if (createdResource instanceof Resource) { Resource resource = (Resource) createdResource; System.out.println("Created: " + resource.id()); if (resource instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine) resource; Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } else if (resource instanceof Network) { Network network = (Network) resource; Assertions.assertTrue(networkNames.contains(network.name())); Assertions.assertNotNull(network.id()); } else if (resource instanceof PublicIpAddress) { PublicIpAddress publicIPAddress = (PublicIpAddress) resource; Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name())); Assertions.assertNotNull(publicIPAddress.id()); } } resourceCount.incrementAndGet(); return createdResource; }) .blockLast(); networkNames.forEach(name -> { Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name)); }); publicIPAddressNames.forEach(name -> { Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name)); }); Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, resourceCount.get()); } @Test public void canSetStorageAccountForUnmanagedDisk() { final String storageName = generateRandomResourceName("st", 14); StorageAccount storageAccount = storageManager .storageAccounts() .define(storageName) .withRegion(region) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.PREMIUM_LRS) .create(); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withUnmanagedDisks() .defineUnmanagedDataDisk("disk1") .withNewVhd(100) .withLun(2) .storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .attach() .defineUnmanagedDataDisk("disk2") .withNewVhd(100) .withLun(3) .storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .attach() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .create(); Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2); Assertions.assertNotNull(firstUnmanagedDataDisk); VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3); Assertions.assertNotNull(secondUnmanagedDataDisk); String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri(); String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri(); Assertions.assertNotNull(createdVhdUri1); Assertions.assertNotNull(createdVhdUri2); computeManager.virtualMachines().deleteById(virtualMachine.id()); virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withUnmanagedDisks() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(1, unmanagedDataDisks.size()); firstUnmanagedDataDisk = null; for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) { firstUnmanagedDataDisk = unmanagedDisk; break; } Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri()); Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1)); virtualMachine .update() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .apply(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); } @Test public void canUpdateTagsOnVM() { VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); virtualMachine.update().withTag("test", "testValue").apply(); Assertions.assertEquals("testValue", virtualMachine.innerModel().tags().get("test")); Map<String, String> testTags = new HashMap<String, String>(); testTags.put("testTag", "testValue"); virtualMachine.update().withTags(testTags).apply(); Assertions.assertEquals(testTags.get("testTag"), virtualMachine.innerModel().tags().get("testTag")); } @Test public void canRunScriptOnVM() { VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .create(); List<String> installGit = new ArrayList<>(); installGit.add("sudo apt-get update"); installGit.add("sudo apt-get install -y git"); RunCommandResult runResult = virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>()); Assertions.assertNotNull(runResult); Assertions.assertNotNull(runResult.value()); Assertions.assertTrue(runResult.value().size() > 0); } @Test @DoNotRecord(skipInPlayback = true) public void canPerformSimulateEvictionOnSpotVirtualMachine() { VirtualMachine virtualMachine = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("firstuser") .withSsh(sshPublicKey()) .withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertTrue(virtualMachine.osDiskSize() > 0); Disk disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertNotNull(disk); Assertions.assertEquals(DiskState.ATTACHED, disk.innerModel().diskState()); virtualMachine.simulateEviction(); boolean deallocated = false; int pollIntervalInMinutes = 5; for (int i = 0; i < 30; i += pollIntervalInMinutes) { ResourceManagerUtils.sleep(Duration.ofMinutes(pollIntervalInMinutes)); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); if (virtualMachine.powerState() == PowerState.DEALLOCATED) { deallocated = true; break; } } Assertions.assertTrue(deallocated); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); Assertions.assertNotNull(virtualMachine); Assertions.assertNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertEquals(0, virtualMachine.osDiskSize()); disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertEquals(DiskState.RESERVED, disk.innerModel().diskState()); } @Test public void canForceDeleteVirtualMachine() { computeManager.virtualMachines() .define(vmName) .withRegion("eastus2euap") .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .create(); VirtualMachine virtualMachine = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(virtualMachine); Assertions.assertEquals(Region.fromName("eastus2euap"), virtualMachine.region()); String nicId = virtualMachine.primaryNetworkInterfaceId(); computeManager.virtualMachines().deleteById(virtualMachine.id(), true); try { virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException ex) { virtualMachine = null; Assertions.assertEquals(404, ex.getResponse().getStatusCode()); } Assertions.assertNull(virtualMachine); NetworkInterface nic = networkManager.networkInterfaces().getById(nicId); Assertions.assertNotNull(nic); } @Test public void canCreateVirtualMachineWithDeleteOption() throws Exception { Region region = Region.US_WEST3; final String publicIpDnsLabel = generateRandomResourceName("pip", 20); Network network = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("default", "10.0.0.0/24") .create(); VirtualMachine vm1 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel/*, DeleteOptions.DELETE*/) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withNewDataDisk(computeManager.disks() .define("datadisk2") .withRegion(region) .withExistingResourceGroup(rgName) .withData() .withSizeInGB(10)) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(DeleteOptions.DELETE, vm1.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(0).deleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(1).deleteOptions()); Assertions.assertEquals(vm1.id(), computeManager.virtualMachines().getById(vm1.id()).id()); computeManager.virtualMachines().deleteById(vm1.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(2, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); PublicIpAddress publicIpAddress = computeManager.networkManager().publicIpAddresses().listByResourceGroup(rgName).stream().findFirst().get(); computeManager.networkManager().publicIpAddresses().deleteById(publicIpAddress.id()); String secondaryNicName = generateRandomResourceName("nic", 10); Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable = this .networkManager .networkInterfaces() .define(secondaryNicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic(); VirtualMachine vm2 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable, DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); computeManager.virtualMachines().deleteById(vm2.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(1, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); secondaryNetworkInterfaceCreatable = this .networkManager .networkInterfaces() .define(secondaryNicName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic(); VirtualMachine vm3 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withNewDataDisk(computeManager.disks() .define("datadisk2") .withRegion(region) .withExistingResourceGroup(rgName) .withData() .withSizeInGB(10)) .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(DeleteOptions.DETACH, vm3.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(0).deleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(1).deleteOptions()); computeManager.virtualMachines().deleteById(vm3.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(3, computeManager.disks().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(2, computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count()); } @Test public void canUpdateVirtualMachineWithDeleteOption() throws Exception { Region region = Region.US_WEST3; Network network = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("default", "10.0.0.0/24") .create(); VirtualMachine vm1 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .withOSDiskDeleteOptions(DeleteOptions.DELETE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); vm1.update() .withNewDataDisk(10) .apply(); computeManager.virtualMachines().deleteById(vm1.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(1, computeManager.disks().listByResourceGroup(rgName).stream().count()); Disk disk = computeManager.disks().listByResourceGroup(rgName).stream().findFirst().get(); computeManager.disks().deleteById(disk.id()); VirtualMachine vm2 = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet("default") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) .withNewDataDisk(10) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); vm2.update() .withNewDataDisk(10) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .apply(); computeManager.virtualMachines().deleteById(vm2.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Assertions.assertEquals(2, computeManager.disks().listByResourceGroup(rgName).stream().count()); } @Test public void canHibernateVirtualMachine() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion("eastus2euap") .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3) .enableHibernation() .create(); Assertions.assertTrue(vm.isHibernationEnabled()); vm.deallocate(true); InstanceViewStatus hibernationStatus = vm.instanceView().statuses().stream() .filter(status -> "HibernationState/Hibernated".equals(status.code())) .findFirst().orElse(null); Assertions.assertNotNull(hibernationStatus); vm.start(); vm.deallocate(); vm.update() .disableHibernation() .apply(); Assertions.assertFalse(vm.isHibernationEnabled()); } @Test public void canOperateVirtualMachine() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_A1_V2) .create(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.redeploy(); vm.powerOff(true); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.STOPPED, vm.powerState()); vm.start(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.restart(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.RUNNING, vm.powerState()); vm.deallocate(); vm.refreshInstanceView(); Assertions.assertEquals(PowerState.DEALLOCATED, vm.powerState()); } @Test public void canCreateVirtualMachineWithEphemeralOSDisk() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) .withEphemeralOSDisk() .withPlacement(DiffDiskPlacement.CACHE_DISK) .withNewDataDisk(1, 1, CachingTypes.READ_WRITE) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertNull(vm.osDiskDiskEncryptionSetId()); Assertions.assertTrue(vm.osDiskSize() > 0); Assertions.assertEquals(vm.osDiskDeleteOptions(), DeleteOptions.DELETE); Assertions.assertEquals(vm.osDiskCachingType(), CachingTypes.READ_ONLY); Assertions.assertFalse(CoreUtils.isNullOrEmpty(vm.dataDisks())); Assertions.assertTrue(vm.isOSDiskEphemeral()); Assertions.assertNotNull(vm.osDiskId()); String osDiskId = vm.osDiskId(); vm.update() .withoutDataDisk(1) .withNewDataDisk(1, 2, CachingTypes.NONE) .withNewDataDisk(1) .apply(); Assertions.assertEquals(vm.dataDisks().size(), 2); vm.powerOff(); vm.start(); vm.refresh(); Assertions.assertEquals(osDiskId, vm.osDiskId()); Assertions.assertThrows(Exception.class, vm::deallocate); } @Test public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { final String vmssName = generateRandomResourceName("vmss", 10); Network network = this .networkManager .networks() .define("vmssvnet") .withRegion(region.name()) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().getByName(rgName); LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); VirtualMachineScaleSet flexibleVMSS = this.computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(rgName) .withFlexibleOrchestrationMode() .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_DS1_V2) .withExistingPrimaryNetworkSubnet(network, "subnet1") .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .withoutPrimaryInternalLoadBalancer() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withCapacity(1) .withUpgradeMode(UpgradeMode.AUTOMATIC) .create(); String regularVMName = generateRandomResourceName("vm", 10); final String pipDnsLabel = generateRandomResourceName("pip", 10); VirtualMachine regularVM = this.computeManager .virtualMachines() .define(regularVMName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(pipDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("jvuser2") .withSsh(sshPublicKey()) .withExistingVirtualMachineScaleSet(flexibleVMSS) .create(); flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.id(), regularVM.virtualMachineScaleSetId()); Assertions.assertEquals(2, flexibleVMSS.capacity()); regularVM.deallocate(); Assertions.assertEquals(regularVM.powerState(), PowerState.DEALLOCATED); this.computeManager .virtualMachines().deleteById(regularVM.id()); flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.capacity(), 1); final String storageAccountName = generateRandomResourceName("stg", 17); Assertions.assertThrows( ApiErrorException.class, () -> computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withLatestLinuxImage("Canonical", "UbuntuServer", "14.04.2-LTS") .withRootUsername("jvuser3") .withSsh(sshPublicKey()) .withUnmanagedDisks() /* UN-MANAGED OS and DATA DISKS */ .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withNewStorageAccount(storageAccountName) .withOSDiskCaching(CachingTypes.READ_WRITE) .withExistingVirtualMachineScaleSet(flexibleVMSS) .create() ); final String vmssName2 = generateRandomResourceName("vmss", 10); Network network2 = this .networkManager .networks() .define("vmssvnet2") .withRegion(region.name()) .withExistingResourceGroup(rgName) .withAddressSpace("192.168.0.0/28") .withSubnet("subnet2", "192.168.0.0/28") .create(); LoadBalancer publicLoadBalancer2 = createHttpLoadBalancers(region, resourceGroup, "2", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); VirtualMachineScaleSet uniformVMSS = this.computeManager .virtualMachineScaleSets() .define(vmssName2) .withRegion(region) .withNewResourceGroup(rgName) .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) .withExistingPrimaryNetworkSubnet(network2, "subnet2") .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer2) .withoutPrimaryInternalLoadBalancer() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser4") .withSsh(sshPublicKey()) .withCapacity(1) .create(); Assertions.assertTrue(uniformVMSS.virtualMachines().list().stream().allMatch(v -> v.instanceId() != null)); String regularVMName2 = generateRandomResourceName("vm", 10); Assertions.assertThrows( ApiErrorException.class, () -> this.computeManager .virtualMachines() .define(regularVMName2) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.1.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("jvuser5") .withSsh(sshPublicKey()) .withExistingVirtualMachineScaleSet(uniformVMSS) .create() ); } @Test @DoNotRecord(skipInPlayback = true) public void canSwapOSDiskWithManagedDisk() { String storageAccountName = generateRandomResourceName("sa", 15); StorageAccount storageAccount = this.storageManager .storageAccounts() .define(storageAccountName) .withRegion(region) .withNewResourceGroup(rgName) .create(); String vm1Name = generateRandomResourceName("vm", 15); VirtualMachine vm1 = this.computeManager .virtualMachines() .define(vm1Name) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/24") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withNewDataDisk(10, 1, CachingTypes.READ_WRITE) .withOSDiskDeleteOptions(DeleteOptions.DETACH) .withExistingStorageAccount(storageAccount) .create(); Disk vm1OSDisk = this.computeManager.disks().getById(vm1.osDiskId()); Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_KEY, vm1OSDisk.encryption().type()); String vaultName = generateRandomResourceName("vault", 15); Vault vault = this.keyVaultManager .vaults() .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientIdFromFile()) .allowKeyPermissions(KeyPermissions.CREATE) .attach() .create(); String keyName = generateRandomResourceName("key", 15); Key key = vault.keys() .define(keyName) .withKeyTypeToCreate(KeyType.RSA) .withKeySize(4096) .create(); String desName = generateRandomResourceName("des", 15); DiskEncryptionSet des = this.computeManager.diskEncryptionSets() .define(desName) .withRegion(region) .withExistingResourceGroup(rgName) .withEncryptionType(DiskEncryptionSetType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY) .withExistingKeyVault(vault.id()) .withExistingKey(key.id()) .withSystemAssignedManagedServiceIdentity() .create(); vault.update() .defineAccessPolicy() .forObjectId(des.systemAssignedManagedServiceIdentityPrincipalId()) .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.UNWRAP_KEY, KeyPermissions.WRAP_KEY) .attach() .withPurgeProtectionEnabled() .apply(); String vm2Name = generateRandomResourceName("vm", 15); VirtualMachine vm2 = this.computeManager.virtualMachines() .define(vm2Name) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/24") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withOSDiskDiskEncryptionSet(des.id()) .withOSDiskDeleteOptions(DeleteOptions.DETACH) .create(); String vm2OSDiskId = vm2.osDiskId(); this.computeManager.virtualMachines().deleteById(vm2.id()); Disk vm2OSDisk = this.computeManager.disks().getById(vm2OSDiskId); Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY, vm2OSDisk.encryption().type()); vm1.deallocate(); vm1.update() .withOSDisk(vm2OSDiskId) .apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm2OSDiskId); Assertions.assertTrue(des.id().equalsIgnoreCase(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet().id())); vm1.deallocate(); vm1.update() .withOSDisk(vm1OSDisk) .apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm1OSDisk.id()); Assertions.assertNull(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet()); } @Test public void canCRUDTrustedLaunchVM() { VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(Region.US_WEST3) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_20_04_LTS_GEN2) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withTrustedLaunch() .withSecureBoot() .withVTpm() .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) .create(); Assertions.assertEquals(SecurityTypes.TRUSTED_LAUNCH, vm.securityType()); Assertions.assertTrue(vm.isSecureBootEnabled()); Assertions.assertTrue(vm.isVTpmEnabled()); vm.update() .withoutSecureBoot() .withoutVTpm() .applyAsync() .flatMap(VirtualMachine::restartAsync) .block(); ResourceManagerUtils.sleep(Duration.ofMinutes(1)); vm = computeManager.virtualMachines().getById(vm.id()); Assertions.assertEquals(SecurityTypes.TRUSTED_LAUNCH, vm.securityType()); Assertions.assertFalse(vm.isSecureBootEnabled()); Assertions.assertFalse(vm.isVTpmEnabled()); computeManager.virtualMachines().deleteById(vm.id()); } @Test private CreatablesInfo prepareCreatableVirtualMachines( Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) { Creatable<ResourceGroup> resourceGroupCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); Creatable<StorageAccount> storageAccountCreatable = storageManager .storageAccounts() .define(generateRandomResourceName("stg", 20)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); List<String> networkCreatableKeys = new ArrayList<>(); List<String> publicIpCreatableKeys = new ArrayList<>(); List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>(); for (int i = 0; i < vmCount; i++) { Creatable<Network> networkCreatable = networkManager .networks() .define(String.format("%s-%d", networkNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withAddressSpace("10.0.0.0/28"); networkCreatableKeys.add(networkCreatable.key()); Creatable<PublicIpAddress> publicIPAddressCreatable = networkManager .publicIpAddresses() .define(String.format("%s-%d", publicIpNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); publicIpCreatableKeys.add(publicIPAddressCreatable.key()); Creatable<VirtualMachine> virtualMachineCreatable = computeManager .virtualMachines() .define(String.format("%s-%d", vmNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withNewPrimaryNetwork(networkCreatable) .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("tirekicker") .withSsh(sshPublicKey()) .withUnmanagedDisks() .withNewStorageAccount(storageAccountCreatable); virtualMachineCreatables.add(virtualMachineCreatable); } CreatablesInfo creatablesInfo = new CreatablesInfo(); creatablesInfo.virtualMachineCreatables = virtualMachineCreatables; creatablesInfo.networkCreatableKeys = networkCreatableKeys; creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys; return creatablesInfo; } class CreatablesInfo { private List<Creatable<VirtualMachine>> virtualMachineCreatables; List<String> networkCreatableKeys; List<String> publicIpCreatableKeys; } }
Should this still be BulkExecutorTest? Shouldn't this be CosmosBulkAsyncTest?
public void executeBulk_preserveOrdering_OnServiceUnAvailable() { int totalRequest = 100; List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String duplicateId = UUID.randomUUID().toString(); PartitionKey duplicatePartitionKey = new PartitionKey(duplicatePK); for (int i = 0; i < totalRequest; i++) { if (i == 0) { BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(duplicateId, 2, 4, "type1", duplicatePK); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, duplicatePartitionKey)); } else { cosmosItemOperations.add(CosmosBulkOperations.getPatchItemOperation(duplicateId, new PartitionKey(duplicatePK), CosmosPatchOperations.create().replace("/type", "updated" + i))); } } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setOrderingPreserved(cosmosBulkExecutionOptions, true); FaultInjectionRule rule = injectBatchFailure("ServiceUnavailable", FaultInjectionServerErrorType.SERVICE_UNAVAILABLE, 1); Flux<CosmosItemOperation> inputFlux = Flux .fromIterable(cosmosItemOperations) .delayElements(Duration.ofMillis(100)); final BulkExecutorWithOrderingPreserved<BulkExecutorTest> executor = new BulkExecutorWithOrderingPreserved<>( this.bulkAsyncContainer, inputFlux, cosmosBulkExecutionOptions); CosmosFaultInjectionHelper .configureFaultInjectionRules(this.bulkAsyncContainer, Arrays.asList(rule)) .block(); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = Flux.deferContextual(context -> executor.execute()).collect(Collectors.toList()).block(); try { assertThat(bulkResponse.size()).isEqualTo(totalRequest); for (int i = 0; i < cosmosItemOperations.size(); i++) { CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(i); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); } } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } rule.disable(); } }
final BulkExecutorWithOrderingPreserved<BulkExecutorTest> executor = new BulkExecutorWithOrderingPreserved<>(
public void executeBulk_preserveOrdering_OnServiceUnAvailable() { int totalRequest = 100; List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String duplicateId = UUID.randomUUID().toString(); PartitionKey duplicatePartitionKey = new PartitionKey(duplicatePK); for (int i = 0; i < totalRequest; i++) { if (i == 0) { BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(duplicateId, 2, 4, "type1", duplicatePK); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, duplicatePartitionKey)); } else { cosmosItemOperations.add(CosmosBulkOperations.getPatchItemOperation(duplicateId, new PartitionKey(duplicatePK), CosmosPatchOperations.create().replace("/type", "updated" + i))); } } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setOrderingPreserved(cosmosBulkExecutionOptions, true); FaultInjectionRule rule = injectBatchFailure("ServiceUnavailable", FaultInjectionServerErrorType.SERVICE_UNAVAILABLE, 1); Flux<CosmosItemOperation> inputFlux = Flux .fromIterable(cosmosItemOperations) .delayElements(Duration.ofMillis(100)); final BulkExecutorWithOrderingPreserved<CosmosBulkAsyncTest> executor = new BulkExecutorWithOrderingPreserved<>( this.bulkAsyncContainer, inputFlux, cosmosBulkExecutionOptions); CosmosFaultInjectionHelper .configureFaultInjectionRules(this.bulkAsyncContainer, Arrays.asList(rule)) .block(); List<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> bulkResponse = Flux.deferContextual(context -> executor.execute()).collect(Collectors.toList()).block(); try { assertThat(bulkResponse.size()).isEqualTo(totalRequest); for (int i = 0; i < cosmosItemOperations.size(); i++) { CosmosBulkOperationResponse<CosmosBulkAsyncTest> operationResponse = bulkResponse.get(i); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); } } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } rule.disable(); } }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 2) public void createItem_withBulkAndThroughputControlAsDefaultGroup() throws InterruptedException { runBulkTest(true); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 2) public void createItem_withBulkAndThroughputControlAsNonDefaultGroup() throws InterruptedException { runBulkTest(false); } private void runBulkTest(boolean isDefaultTestGroup) throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .groupName("test-group") .targetThroughputThreshold(0.2) .defaultControlGroup(isDefaultTestGroup) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); if (!isDefaultTestGroup) { cosmosBulkExecutionOptions.setThroughputControlGroupName("test-group"); } try { Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk_after_collectionRecreate() { int totalRequest = getTotalRequest(); for(int x = 0; x < 2; x = x + 1) { Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); CosmosAsyncDatabase db = bulkAsyncContainer .getDatabase(); String containerName = bulkAsyncContainer.getId(); bulkAsyncContainer.delete().block(); db .createContainer( containerName, "/mypk", ThroughputProperties.createManualThroughput(10_100)) .block(); bulkAsyncContainer = db.getContainer(containerName); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk_and_operationLevelContext() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String randomId = UUID.randomUUID().toString(); String partitionKey = randomId; TestDoc testDoc = this.populateTestDoc(partitionKey); ItemOperationContext ctx = new ItemOperationContext(randomId); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey), ctx); }), Flux.range(0, totalRequest).map(i -> { String randomId = UUID.randomUUID().toString(); String partitionKey = randomId; EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); ItemOperationContext ctx = new ItemOperationContext(randomId); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey), ctx); })); CosmosBulkExecutionOptions bulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setTargetedMicroBatchRetryRate( bulkExecutionOptions, 0.25, 0.5); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, bulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); ItemOperationContext ctx = cosmosBulkOperationResponse.getOperation().getContext(); assertThat(cosmosBulkOperationResponse.getOperation().getPartitionKeyValue().toString()) .isEqualTo(new PartitionKey(ctx.getCorrelationId()).toString()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); createResponseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(deleteCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(readCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .executeBulkOperations(readCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(replaceCosmosItemOperationFlux) .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations) { CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } @DataProvider() public Object[][] faultInjectionProvider() { return new Object[][]{ {null}, {injectBatchFailure("RequestRateTooLarge", FaultInjectionServerErrorType.TOO_MANY_REQUEST, 10)}, {injectBatchFailure("PartitionSplit", FaultInjectionServerErrorType.PARTITION_IS_SPLITTING, 2)} }; } @Test(groups = { "simple" }, timeOut = TIMEOUT * 30, dataProvider = "faultInjectionProvider") public void executeBulk_preserveOrdering_OnFaults(FaultInjectionRule rule) { int totalRequest = 100; List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); for (int i = 0; i < totalRequest; i++) { if (i == 0) { BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(duplicatePK))); } else { cosmosItemOperations.add(CosmosBulkOperations.getPatchItemOperation(id, new PartitionKey(duplicatePK), CosmosPatchOperations.create().replace("/type", "updated" + i))); } } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setOrderingPreserved(cosmosBulkExecutionOptions, true); Flux<CosmosItemOperation> inputFlux = Flux .fromIterable(cosmosItemOperations) .delayElements(Duration.ofMillis(100)); final BulkExecutorWithOrderingPreserved<BulkExecutorTest> executor = new BulkExecutorWithOrderingPreserved<>( this.bulkAsyncContainer, inputFlux, cosmosBulkExecutionOptions); if (rule != null) { CosmosFaultInjectionHelper .configureFaultInjectionRules(this.bulkAsyncContainer, Arrays.asList(rule)) .block(); } List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = Flux.deferContextual(context -> executor.execute()).collect(Collectors.toList()).block(); try { assertThat(bulkResponse.size()).isEqualTo(totalRequest); for (int i = 0; i < cosmosItemOperations.size(); i++) { CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(i); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(operationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(i)); if (i == 0) { assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); } else { assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); } assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); } } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } if (rule != null) { rule.disable(); } } } @Test(groups = { "simple" }, timeOut = TIMEOUT) private FaultInjectionRule injectBatchFailure(String id, FaultInjectionServerErrorType serverErrorType, int hitLimit) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .delay(Duration.ofMillis(1500)); IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionConnectionType connectionType = FaultInjectionConnectionType.GATEWAY; if (ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getConnectionMode(this.bulkClient) .equals(ConnectionMode.DIRECT.toString())) { connectionType = FaultInjectionConnectionType.DIRECT; } FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .connectionType(connectionType) .build(); return new FaultInjectionRuleBuilder(id) .condition(condition) .result(result) .startDelay(Duration.ofSeconds(1)) .hitLimit(hitLimit) .build(); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } private static class ItemOperationContext { private final String correlationId; public ItemOperationContext(String correlationId) { this.correlationId = correlationId; } public String getCorrelationId() { return this.correlationId; } } }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 2) public void createItem_withBulkAndThroughputControlAsDefaultGroup() throws InterruptedException { runBulkTest(true); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 2) public void createItem_withBulkAndThroughputControlAsNonDefaultGroup() throws InterruptedException { runBulkTest(false); } private void runBulkTest(boolean isDefaultTestGroup) throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .groupName("test-group") .targetThroughputThreshold(0.2) .defaultControlGroup(isDefaultTestGroup) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); if (!isDefaultTestGroup) { cosmosBulkExecutionOptions.setThroughputControlGroupName("test-group"); } try { Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk_after_collectionRecreate() { int totalRequest = getTotalRequest(); for(int x = 0; x < 2; x = x + 1) { Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); CosmosAsyncDatabase db = bulkAsyncContainer .getDatabase(); String containerName = bulkAsyncContainer.getId(); bulkAsyncContainer.delete().block(); db .createContainer( containerName, "/mypk", ThroughputProperties.createManualThroughput(10_100)) .block(); bulkAsyncContainer = db.getContainer(containerName); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk_and_operationLevelContext() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String randomId = UUID.randomUUID().toString(); String partitionKey = randomId; TestDoc testDoc = this.populateTestDoc(partitionKey); ItemOperationContext ctx = new ItemOperationContext(randomId); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey), ctx); }), Flux.range(0, totalRequest).map(i -> { String randomId = UUID.randomUUID().toString(); String partitionKey = randomId; EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); ItemOperationContext ctx = new ItemOperationContext(randomId); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey), ctx); })); CosmosBulkExecutionOptions bulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setTargetedMicroBatchRetryRate( bulkExecutionOptions, 0.25, 0.5); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, bulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); ItemOperationContext ctx = cosmosBulkOperationResponse.getOperation().getContext(); assertThat(cosmosBulkOperationResponse.getOperation().getPartitionKeyValue().toString()) .isEqualTo(new PartitionKey(ctx.getCorrelationId()).toString()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); createResponseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(deleteCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(readCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .executeBulkOperations(readCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(replaceCosmosItemOperationFlux) .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations) { CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } @DataProvider() public Object[][] faultInjectionProvider() { return new Object[][]{ {null}, {injectBatchFailure("RequestRateTooLarge", FaultInjectionServerErrorType.TOO_MANY_REQUEST, 10)}, {injectBatchFailure("PartitionSplit", FaultInjectionServerErrorType.PARTITION_IS_SPLITTING, 2)} }; } @Test(groups = { "simple" }, timeOut = TIMEOUT * 30, dataProvider = "faultInjectionProvider") public void executeBulk_preserveOrdering_OnFaults(FaultInjectionRule rule) { int totalRequest = 100; List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); for (int i = 0; i < totalRequest; i++) { if (i == 0) { BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(duplicatePK))); } else { cosmosItemOperations.add(CosmosBulkOperations.getPatchItemOperation(id, new PartitionKey(duplicatePK), CosmosPatchOperations.create().replace("/type", "updated" + i))); } } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setOrderingPreserved(cosmosBulkExecutionOptions, true); Flux<CosmosItemOperation> inputFlux = Flux .fromIterable(cosmosItemOperations) .delayElements(Duration.ofMillis(100)); final BulkExecutorWithOrderingPreserved<CosmosBulkAsyncTest> executor = new BulkExecutorWithOrderingPreserved<>( this.bulkAsyncContainer, inputFlux, cosmosBulkExecutionOptions); if (rule != null) { CosmosFaultInjectionHelper .configureFaultInjectionRules(this.bulkAsyncContainer, Arrays.asList(rule)) .block(); } List<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> bulkResponse = Flux.deferContextual(context -> executor.execute()).collect(Collectors.toList()).block(); try { assertThat(bulkResponse.size()).isEqualTo(totalRequest); for (int i = 0; i < cosmosItemOperations.size(); i++) { CosmosBulkOperationResponse<CosmosBulkAsyncTest> operationResponse = bulkResponse.get(i); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(operationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(i)); if (i == 0) { assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); } else { assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); } assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); } } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } if (rule != null) { rule.disable(); } } } @Test(groups = { "simple" }, timeOut = TIMEOUT) private FaultInjectionRule injectBatchFailure(String id, FaultInjectionServerErrorType serverErrorType, int hitLimit) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .delay(Duration.ofMillis(1500)); IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionConnectionType connectionType = FaultInjectionConnectionType.GATEWAY; if (ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getConnectionMode(this.bulkClient) .equals(ConnectionMode.DIRECT.toString())) { connectionType = FaultInjectionConnectionType.DIRECT; } FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .connectionType(connectionType) .build(); return new FaultInjectionRuleBuilder(id) .condition(condition) .result(result) .startDelay(Duration.ofSeconds(1)) .hitLimit(hitLimit) .build(); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } private static class ItemOperationContext { private final String correlationId; public ItemOperationContext(String correlationId) { this.correlationId = correlationId; } public String getCorrelationId() { return this.correlationId; } } }
Changed to CosmosBulkAsyncTest
public void executeBulk_preserveOrdering_OnServiceUnAvailable() { int totalRequest = 100; List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String duplicateId = UUID.randomUUID().toString(); PartitionKey duplicatePartitionKey = new PartitionKey(duplicatePK); for (int i = 0; i < totalRequest; i++) { if (i == 0) { BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(duplicateId, 2, 4, "type1", duplicatePK); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, duplicatePartitionKey)); } else { cosmosItemOperations.add(CosmosBulkOperations.getPatchItemOperation(duplicateId, new PartitionKey(duplicatePK), CosmosPatchOperations.create().replace("/type", "updated" + i))); } } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setOrderingPreserved(cosmosBulkExecutionOptions, true); FaultInjectionRule rule = injectBatchFailure("ServiceUnavailable", FaultInjectionServerErrorType.SERVICE_UNAVAILABLE, 1); Flux<CosmosItemOperation> inputFlux = Flux .fromIterable(cosmosItemOperations) .delayElements(Duration.ofMillis(100)); final BulkExecutorWithOrderingPreserved<BulkExecutorTest> executor = new BulkExecutorWithOrderingPreserved<>( this.bulkAsyncContainer, inputFlux, cosmosBulkExecutionOptions); CosmosFaultInjectionHelper .configureFaultInjectionRules(this.bulkAsyncContainer, Arrays.asList(rule)) .block(); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = Flux.deferContextual(context -> executor.execute()).collect(Collectors.toList()).block(); try { assertThat(bulkResponse.size()).isEqualTo(totalRequest); for (int i = 0; i < cosmosItemOperations.size(); i++) { CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(i); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); } } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } rule.disable(); } }
final BulkExecutorWithOrderingPreserved<BulkExecutorTest> executor = new BulkExecutorWithOrderingPreserved<>(
public void executeBulk_preserveOrdering_OnServiceUnAvailable() { int totalRequest = 100; List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String duplicateId = UUID.randomUUID().toString(); PartitionKey duplicatePartitionKey = new PartitionKey(duplicatePK); for (int i = 0; i < totalRequest; i++) { if (i == 0) { BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(duplicateId, 2, 4, "type1", duplicatePK); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, duplicatePartitionKey)); } else { cosmosItemOperations.add(CosmosBulkOperations.getPatchItemOperation(duplicateId, new PartitionKey(duplicatePK), CosmosPatchOperations.create().replace("/type", "updated" + i))); } } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setOrderingPreserved(cosmosBulkExecutionOptions, true); FaultInjectionRule rule = injectBatchFailure("ServiceUnavailable", FaultInjectionServerErrorType.SERVICE_UNAVAILABLE, 1); Flux<CosmosItemOperation> inputFlux = Flux .fromIterable(cosmosItemOperations) .delayElements(Duration.ofMillis(100)); final BulkExecutorWithOrderingPreserved<CosmosBulkAsyncTest> executor = new BulkExecutorWithOrderingPreserved<>( this.bulkAsyncContainer, inputFlux, cosmosBulkExecutionOptions); CosmosFaultInjectionHelper .configureFaultInjectionRules(this.bulkAsyncContainer, Arrays.asList(rule)) .block(); List<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> bulkResponse = Flux.deferContextual(context -> executor.execute()).collect(Collectors.toList()).block(); try { assertThat(bulkResponse.size()).isEqualTo(totalRequest); for (int i = 0; i < cosmosItemOperations.size(); i++) { CosmosBulkOperationResponse<CosmosBulkAsyncTest> operationResponse = bulkResponse.get(i); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); } } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } rule.disable(); } }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 2) public void createItem_withBulkAndThroughputControlAsDefaultGroup() throws InterruptedException { runBulkTest(true); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 2) public void createItem_withBulkAndThroughputControlAsNonDefaultGroup() throws InterruptedException { runBulkTest(false); } private void runBulkTest(boolean isDefaultTestGroup) throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .groupName("test-group") .targetThroughputThreshold(0.2) .defaultControlGroup(isDefaultTestGroup) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); if (!isDefaultTestGroup) { cosmosBulkExecutionOptions.setThroughputControlGroupName("test-group"); } try { Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk_after_collectionRecreate() { int totalRequest = getTotalRequest(); for(int x = 0; x < 2; x = x + 1) { Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); CosmosAsyncDatabase db = bulkAsyncContainer .getDatabase(); String containerName = bulkAsyncContainer.getId(); bulkAsyncContainer.delete().block(); db .createContainer( containerName, "/mypk", ThroughputProperties.createManualThroughput(10_100)) .block(); bulkAsyncContainer = db.getContainer(containerName); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk_and_operationLevelContext() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String randomId = UUID.randomUUID().toString(); String partitionKey = randomId; TestDoc testDoc = this.populateTestDoc(partitionKey); ItemOperationContext ctx = new ItemOperationContext(randomId); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey), ctx); }), Flux.range(0, totalRequest).map(i -> { String randomId = UUID.randomUUID().toString(); String partitionKey = randomId; EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); ItemOperationContext ctx = new ItemOperationContext(randomId); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey), ctx); })); CosmosBulkExecutionOptions bulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setTargetedMicroBatchRetryRate( bulkExecutionOptions, 0.25, 0.5); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, bulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); ItemOperationContext ctx = cosmosBulkOperationResponse.getOperation().getContext(); assertThat(cosmosBulkOperationResponse.getOperation().getPartitionKeyValue().toString()) .isEqualTo(new PartitionKey(ctx.getCorrelationId()).toString()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); createResponseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(deleteCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(readCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .executeBulkOperations(readCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(replaceCosmosItemOperationFlux) .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations) { CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } @DataProvider() public Object[][] faultInjectionProvider() { return new Object[][]{ {null}, {injectBatchFailure("RequestRateTooLarge", FaultInjectionServerErrorType.TOO_MANY_REQUEST, 10)}, {injectBatchFailure("PartitionSplit", FaultInjectionServerErrorType.PARTITION_IS_SPLITTING, 2)} }; } @Test(groups = { "simple" }, timeOut = TIMEOUT * 30, dataProvider = "faultInjectionProvider") public void executeBulk_preserveOrdering_OnFaults(FaultInjectionRule rule) { int totalRequest = 100; List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); for (int i = 0; i < totalRequest; i++) { if (i == 0) { BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(duplicatePK))); } else { cosmosItemOperations.add(CosmosBulkOperations.getPatchItemOperation(id, new PartitionKey(duplicatePK), CosmosPatchOperations.create().replace("/type", "updated" + i))); } } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setOrderingPreserved(cosmosBulkExecutionOptions, true); Flux<CosmosItemOperation> inputFlux = Flux .fromIterable(cosmosItemOperations) .delayElements(Duration.ofMillis(100)); final BulkExecutorWithOrderingPreserved<BulkExecutorTest> executor = new BulkExecutorWithOrderingPreserved<>( this.bulkAsyncContainer, inputFlux, cosmosBulkExecutionOptions); if (rule != null) { CosmosFaultInjectionHelper .configureFaultInjectionRules(this.bulkAsyncContainer, Arrays.asList(rule)) .block(); } List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = Flux.deferContextual(context -> executor.execute()).collect(Collectors.toList()).block(); try { assertThat(bulkResponse.size()).isEqualTo(totalRequest); for (int i = 0; i < cosmosItemOperations.size(); i++) { CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(i); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(operationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(i)); if (i == 0) { assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); } else { assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); } assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); } } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } if (rule != null) { rule.disable(); } } } @Test(groups = { "simple" }, timeOut = TIMEOUT) private FaultInjectionRule injectBatchFailure(String id, FaultInjectionServerErrorType serverErrorType, int hitLimit) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .delay(Duration.ofMillis(1500)); IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionConnectionType connectionType = FaultInjectionConnectionType.GATEWAY; if (ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getConnectionMode(this.bulkClient) .equals(ConnectionMode.DIRECT.toString())) { connectionType = FaultInjectionConnectionType.DIRECT; } FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .connectionType(connectionType) .build(); return new FaultInjectionRuleBuilder(id) .condition(condition) .result(result) .startDelay(Duration.ofSeconds(1)) .hitLimit(hitLimit) .build(); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } private static class ItemOperationContext { private final String correlationId; public ItemOperationContext(String correlationId) { this.correlationId = correlationId; } public String getCorrelationId() { return this.correlationId; } } }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 2) public void createItem_withBulkAndThroughputControlAsDefaultGroup() throws InterruptedException { runBulkTest(true); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 2) public void createItem_withBulkAndThroughputControlAsNonDefaultGroup() throws InterruptedException { runBulkTest(false); } private void runBulkTest(boolean isDefaultTestGroup) throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .groupName("test-group") .targetThroughputThreshold(0.2) .defaultControlGroup(isDefaultTestGroup) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); if (!isDefaultTestGroup) { cosmosBulkExecutionOptions.setThroughputControlGroupName("test-group"); } try { Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk_after_collectionRecreate() { int totalRequest = getTotalRequest(); for(int x = 0; x < 2; x = x + 1) { Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); CosmosAsyncDatabase db = bulkAsyncContainer .getDatabase(); String containerName = bulkAsyncContainer.getId(); bulkAsyncContainer.delete().block(); db .createContainer( containerName, "/mypk", ThroughputProperties.createManualThroughput(10_100)) .block(); bulkAsyncContainer = db.getContainer(containerName); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk_and_operationLevelContext() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String randomId = UUID.randomUUID().toString(); String partitionKey = randomId; TestDoc testDoc = this.populateTestDoc(partitionKey); ItemOperationContext ctx = new ItemOperationContext(randomId); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey), ctx); }), Flux.range(0, totalRequest).map(i -> { String randomId = UUID.randomUUID().toString(); String partitionKey = randomId; EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); ItemOperationContext ctx = new ItemOperationContext(randomId); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey), ctx); })); CosmosBulkExecutionOptions bulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setTargetedMicroBatchRetryRate( bulkExecutionOptions, 0.25, 0.5); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, bulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); ItemOperationContext ctx = cosmosBulkOperationResponse.getOperation().getContext(); assertThat(cosmosBulkOperationResponse.getOperation().getPartitionKeyValue().toString()) .isEqualTo(new PartitionKey(ctx.getCorrelationId()).toString()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); createResponseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .executeBulkOperations(cosmosItemOperationFlux, cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(deleteCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(readCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .executeBulkOperations(readCosmosItemOperationFlux, cosmosBulkExecutionOptions) .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<com.azure.cosmos.models.CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((com.azure.cosmos.models.CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return CosmosBulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .executeBulkOperations(replaceCosmosItemOperationFlux) .flatMap((com.azure.cosmos.models.CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations) { CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .executeBulkOperations(Flux.fromIterable(cosmosItemOperations), cosmosBulkExecutionOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap(cosmosBulkOperationResponse -> { processedDoc.incrementAndGet(); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } @DataProvider() public Object[][] faultInjectionProvider() { return new Object[][]{ {null}, {injectBatchFailure("RequestRateTooLarge", FaultInjectionServerErrorType.TOO_MANY_REQUEST, 10)}, {injectBatchFailure("PartitionSplit", FaultInjectionServerErrorType.PARTITION_IS_SPLITTING, 2)} }; } @Test(groups = { "simple" }, timeOut = TIMEOUT * 30, dataProvider = "faultInjectionProvider") public void executeBulk_preserveOrdering_OnFaults(FaultInjectionRule rule) { int totalRequest = 100; List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); for (int i = 0; i < totalRequest; i++) { if (i == 0) { BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(duplicatePK))); } else { cosmosItemOperations.add(CosmosBulkOperations.getPatchItemOperation(id, new PartitionKey(duplicatePK), CosmosPatchOperations.create().replace("/type", "updated" + i))); } } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setOrderingPreserved(cosmosBulkExecutionOptions, true); Flux<CosmosItemOperation> inputFlux = Flux .fromIterable(cosmosItemOperations) .delayElements(Duration.ofMillis(100)); final BulkExecutorWithOrderingPreserved<CosmosBulkAsyncTest> executor = new BulkExecutorWithOrderingPreserved<>( this.bulkAsyncContainer, inputFlux, cosmosBulkExecutionOptions); if (rule != null) { CosmosFaultInjectionHelper .configureFaultInjectionRules(this.bulkAsyncContainer, Arrays.asList(rule)) .block(); } List<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> bulkResponse = Flux.deferContextual(context -> executor.execute()).collect(Collectors.toList()).block(); try { assertThat(bulkResponse.size()).isEqualTo(totalRequest); for (int i = 0; i < cosmosItemOperations.size(); i++) { CosmosBulkOperationResponse<CosmosBulkAsyncTest> operationResponse = bulkResponse.get(i); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(operationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(i)); if (i == 0) { assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); } else { assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); } assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); } } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } if (rule != null) { rule.disable(); } } } @Test(groups = { "simple" }, timeOut = TIMEOUT) private FaultInjectionRule injectBatchFailure(String id, FaultInjectionServerErrorType serverErrorType, int hitLimit) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .delay(Duration.ofMillis(1500)); IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionConnectionType connectionType = FaultInjectionConnectionType.GATEWAY; if (ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getConnectionMode(this.bulkClient) .equals(ConnectionMode.DIRECT.toString())) { connectionType = FaultInjectionConnectionType.DIRECT; } FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .connectionType(connectionType) .build(); return new FaultInjectionRuleBuilder(id) .condition(condition) .result(result) .startDelay(Duration.ofSeconds(1)) .hitLimit(hitLimit) .build(); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } private static class ItemOperationContext { private final String correlationId; public ItemOperationContext(String correlationId) { this.correlationId = correlationId; } public String getCorrelationId() { return this.correlationId; } } }
Does AppGateway work with BASIC ipAddress?
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
.withSku(PublicIPSkuType.STANDARD)
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
No it doesn't... It's more like a V2 SKU to me. > Application Gateway with SKU Basic can only reference public ip with Standard SKU
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
.withSku(PublicIPSkuType.STANDARD)
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
Got it. Do you know whether `withNewPublicIpAddress()` creates an IP address?
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
.withSku(PublicIPSkuType.STANDARD)
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
Yeah, it'll be created in `createInner`, through `ensureDefaultPipDefinition`: https://github.com/Azure/azure-sdk-for-java/blob/654650746b7294af2f81457cde7db9afbbee76e2/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayImpl.java#L563-L573 Maybe we'll set pip sku to `STANDARD` here if it's not legacy gateway.
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
.withSku(PublicIPSkuType.STANDARD)
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
Maybe next year. As currently user can still create V1 (if subscription has V1)
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
.withSku(PublicIPSkuType.STANDARD)
public void canCreateApplicationGatewayWithDefaultSku() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); Assertions.assertNotNull(appGateway.requestRoutingRules().get("rule1").priority()); }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
class ApplicationGatewayTests extends NetworkManagementTest { @Test public void canCRUDApplicationGatewayWithWAF() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertTrue(appGateway != null); Assertions.assertTrue(ApplicationGatewayTier.WAF_V2.equals(appGateway.tier())); Assertions.assertTrue(ApplicationGatewaySkuName.WAF_V2.equals(appGateway.size())); Assertions.assertTrue(appGateway.autoscaleConfiguration().minCapacity() == 2); Assertions.assertTrue(appGateway.autoscaleConfiguration().maxCapacity() == 5); ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); config .withDisabledRuleGroups( Arrays .asList( new ApplicationGatewayFirewallDisabledRuleGroup() .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); config .withExclusions( Arrays .asList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator("StartsWith") .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().fileUploadLimitInMb() == 200); Assertions.assertTrue(appGateway.webApplicationFirewallConfiguration().requestBodyCheck()); Assertions .assertEquals(appGateway.webApplicationFirewallConfiguration().maxRequestBodySizeInKb(), (Integer) 64); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().exclusions().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable(), "RequestHeaderNames"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator(), "StartsWith"); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector(), "User-Agent"); Assertions.assertEquals(appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size(), 1); Assertions .assertEquals( appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName(), "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"); } @Test public void canSpecifyWildcardListeners() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); String listener1 = "listener1"; String hostname1 = "my.contoso.com"; ApplicationGateway gateway = networkManager.applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule80") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .withCookieBasedAffinity() .attach() .defineListener(listener1) .withPublicFrontend() .withFrontendPort(9000) .withHttp() .withHostname(hostname1) .attach() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withExistingPublicIpAddress(pip) .create(); Assertions.assertEquals(hostname1, gateway.listeners().get(listener1).hostname()); String hostname2 = "*.contoso.com"; gateway.update() .updateListener(listener1) .withHostname(hostname2) .parent() .apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); List<String> hostnames = new ArrayList<>(); hostnames.add(hostname1); hostnames.add(hostname2); gateway.update() .updateListener(listener1) .withHostnames(hostnames) .parent() .apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSecret() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); Secret secret1 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); Secret secret2 = createKeyVaultSecret(clientIdFromFile(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secret1.id()) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions .assertEquals( secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); appGateway = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateApplicationGatewayWithSslCertificate() throws Exception { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String identityName = generateRandomResourceName("id", 10); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); Identity identity = msiManager .identities() .define(identityName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); String secretId = createKeyVaultCertificate(clientIdFromFile(), identity.principalId()); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificate("ssl1") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withIdentity(serviceIdentity) .defineSslCertificate("ssl1") .withKeyVaultSecretId(secretId) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .defineRequestRoutingRule("rule2") .fromPublicFrontend() .fromFrontendHttpPort(81) .toBackendHttpPort(8181) .toBackendIPAddress("11.1.1.3") .attach() .defineRequestRoutingRule("rule3") .fromPublicFrontend() .fromFrontendHttpPort(83) .toBackendHttpPort(8383) .toBackendIPAddress("11.1.1.4") .withPriority(1) .attach() .defineRequestRoutingRule("rule4") .fromPublicFrontend() .fromFrontendHttpPort(84) .toBackendHttpPort(8384) .toBackendIPAddress("11.1.1.5") .withPriority(20000) .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); appGateway.update() .defineRequestRoutingRule("rule5") .fromPublicFrontend() .fromFrontendHttpPort(82) .toBackendHttpPort(8282) .toBackendIPAddress("11.1.1.6") .attach() .apply(); Integer rule1Priority = appGateway.requestRoutingRules().get("rule1").priority(); Integer rule2Priority = appGateway.requestRoutingRules().get("rule2").priority(); Integer rule5Priority = appGateway.requestRoutingRules().get("rule5").priority(); Assertions.assertTrue(rule1Priority < rule5Priority && rule2Priority < rule5Priority); Assertions.assertEquals(1, appGateway.requestRoutingRules().get("rule3").priority()); Assertions.assertEquals(20000, appGateway.requestRoutingRules().get("rule4").priority()); appGateway.update() .defineRequestRoutingRule("rule6") .fromPublicFrontend() .fromFrontendHttpPort(85) .toBackendHttpPort(8585) .toBackendIPAddress("11.1.1.7") .attach() .defineRequestRoutingRule("rule7") .fromPublicFrontend() .fromFrontendHttpPort(86) .toBackendHttpPort(8686) .toBackendIPAddress("11.1.1.8") .withPriority(10040) .attach() .apply(); Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); appGateway.update() .updateRequestRoutingRule("rule3") .withPriority(2) .parent() .apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @Test public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withAutoScale(2, 5) .withWebApplicationFirewall( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0") .withExclusions(Collections.singletonList( new ApplicationGatewayFirewallExclusion() .withMatchVariable("RequestHeaderNames") .withSelectorMatchOperator(null) .withSelector(null) )) ) .create(); Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map<String, ApplicationGatewayBackend> backends = appGateway.backends(); backends.forEach((name, backend) -> backend.addresses().forEach(addr -> appGateway.update() .updateBackend(name) .withoutIPAddress(addr.ipAddress()) .parent() .apply())); } @Test public void canAssociateWafPolicy() { String appGatewayName = generateRandomResourceName("agwaf", 15); String appPublicIp = generateRandomResourceName("pip", 15); String wafPolicyName = generateRandomResourceName("waf", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); WebApplicationFirewallPolicy wafPolicy = networkManager .webApplicationFirewallPolicies() .define(wafPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withExistingWebApplicationFirewallPolicy(wafPolicy) .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); wafPolicy.refresh(); Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); appGateway.update() .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) .apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); Assertions.assertNotNull(newPolicy); Assertions.assertTrue(newPolicy.isEnabled()); Assertions.assertEquals(WebApplicationFirewallMode.PREVENTION, newPolicy.mode()); Assertions.assertNotEquals(newPolicy.id(), wafPolicy.id()); Assertions.assertEquals(appGateway.id(), newPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(newPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); String invalidPolicyName = "invalid"; Assertions.assertThrows(IllegalStateException.class, () -> { networkManager.applicationGateways() .define("invalid") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .withNewPublicIpAddress() .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withNewWebApplicationFirewallPolicy( networkManager .webApplicationFirewallPolicies() .define(invalidPolicyName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); Assertions.assertTrue( networkManager .webApplicationFirewallPolicies() .listByResourceGroup(rgName) .stream() .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test public void canSetSslPolicy() { String appGatewayName = generateRandomResourceName("agw", 15); String appPublicIp = generateRandomResourceName("pip", 15); PublicIpAddress pip = networkManager .publicIpAddresses() .define(appPublicIp) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); ApplicationGateway appGateway = networkManager .applicationGateways() .define(appGatewayName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .attach() .withExistingPublicIpAddress(pip) .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.PREDEFINED, sslPolicy.policyType()); Assertions.assertEquals(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501, sslPolicy.policyName()); appGateway.update() .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() .withSslPolicy(new ApplicationGatewaySslPolicy() .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @Test private String createKeyVaultCertificate(String servicePrincipal, String identityPrincipal) { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); return certificate.getSecretId(); } private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() .getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); Vault vault = keyVaultManager .vaults() .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forObjectId(identityPrincipal) .allowSecretAllPermissions() .attach() .withAccessFromAzureServices() .withDeploymentEnabled() .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode userAssignedIdentitiesValueObject = mapper.createObjectNode(); ((ObjectNode) userAssignedIdentitiesValueObject).put("principalId", identity.principalId()); ((ObjectNode) userAssignedIdentitiesValueObject).put("clientId", identity.clientId()); ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = new JacksonAdapter() .deserialize( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userAssignedIdentitiesValueObject), ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map<String, ManagedServiceIdentityUserAssignedIdentities> userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity(); serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED); serviceIdentity.withUserAssignedIdentities(userAssignedIdentities); return serviceIdentity; } }
how moving it here helps? `requestManager can still be null here, right?
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency >= this.nonRespondingChannelReadDelayTimeLimitInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext();
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency >= this.nonRespondingChannelReadDelayTimeLimitInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
`requestManager` is checked for nullability at the beginning of `isHealthyWithFailureReason`. Moving the call `requestManager.rntbdContext()` to within at least guarantees the channel has seen wire reads which would imply RNTBD context negotiation has happened (in-line with how it is done in other health check gates).
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency >= this.nonRespondingChannelReadDelayTimeLimitInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext();
private String isCancellationProneChannel(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String errorMessage = StringUtils.EMPTY; if (timestamps.cancellationCount() >= this.cancellationCountSinceLastReadThreshold) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return errorMessage; } final long readSuccessRecency = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readSuccessRecency >= this.nonRespondingChannelReadDelayTimeLimitInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); errorMessage = MessageFormat.format( "{0} health check failed due to channel being cancellation prone: [rntbdContext: {1}, lastChannelWrite: {2}, lastChannelRead: {3}," + "cancellationCountSinceLastSuccessfulRead: {4}, currentTime: {5}]", channel, rntbdContext, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), timestamps.cancellationCount(), currentTime); logger.warn(errorMessage); return errorMessage; } } return errorMessage; }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
class RntbdClientChannelHealthChecker implements ChannelHealthChecker { private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); private static final long recentReadWindowInNanos = 1_000_000_000L; private static final long readHangGracePeriodInNanos = (45L + 10L) * 1_000_000_000L; private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; @JsonProperty private final long idleConnectionTimeoutInNanos; @JsonProperty private final long readDelayLimitInNanos; @JsonProperty private final long writeDelayLimitInNanos; @JsonProperty private final long networkRequestTimeoutInNanos; @JsonProperty private final boolean timeoutDetectionEnabled; @JsonProperty private final double timeoutDetectionDisableCPUThreshold; @JsonProperty private final long timeoutTimeLimitInNanos; @JsonProperty private final int timeoutHighFrequencyThreshold; @JsonProperty private final long timeoutHighFrequencyTimeLimitInNanos; @JsonProperty private final int timeoutOnWriteThreshold; @JsonProperty private final long timeoutOnWriteTimeLimitInNanos; @JsonProperty private final long nonRespondingChannelReadDelayTimeLimitInNanos; @JsonProperty private final int cancellationCountSinceLastReadThreshold; public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "expected non-null config"); checkArgument(config.receiveHangDetectionTimeInNanos() > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", config.receiveHangDetectionTimeInNanos()); checkArgument(config.sendHangDetectionTimeInNanos() > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", config.sendHangDetectionTimeInNanos()); this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); this.networkRequestTimeoutInNanos = config.tcpNetworkRequestTimeoutInNanos(); this.timeoutDetectionEnabled = config.timeoutDetectionEnabled(); this.timeoutDetectionDisableCPUThreshold = config.timeoutDetectionDisableCPUThreshold(); this.timeoutTimeLimitInNanos = config.timeoutDetectionTimeLimitInNanos(); this.timeoutHighFrequencyThreshold = config.timeoutDetectionHighFrequencyThreshold(); this.timeoutHighFrequencyTimeLimitInNanos = config.timeoutDetectionHighFrequencyTimeLimitInNanos(); this.timeoutOnWriteThreshold = config.timeoutDetectionOnWriteThreshold(); this.timeoutOnWriteTimeLimitInNanos = config.timeoutDetectionOnWriteTimeLimitInNanos(); this.nonRespondingChannelReadDelayTimeLimitInNanos = config.nonRespondingChannelReadDelayTimeLimitInNanos(); this.cancellationCountSinceLastReadThreshold = config.cancellationCountSinceLastReadThreshold(); } /** * Returns the idle connection timeout interval in nanoseconds. * <p> * A channel is considered idle if {@link * the last channel read is greater than {@link * * @return Idle connection timeout interval in nanoseconds. */ public long idleConnectionTimeoutInNanos() { return this.idleConnectionTimeoutInNanos; } /** * Returns the read delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write and the last channel read grows * beyond this value. * <p> * Constraint: {@link * * @return Read delay limit in nanoseconds. */ public long readDelayLimitInNanos() { return this.readDelayLimitInNanos; } /** * Returns the write delay limit in nanoseconds. * <p> * A channel will be declared unhealthy if the gap between the last channel write attempt and the last channel write * grows beyond this value. * <p> * Constraint: {@link * * @return Write delay limit in nanoseconds. */ public long writeDelayLimitInNanos() { return this.writeDelayLimitInNanos; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result of {@code true} if the channel is healthy, or {@code false} otherwise. */ public Future<Boolean> isHealthy(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final Promise<Boolean> promise = channel.eventLoop().newPromise(); this.isHealthyWithFailureReason(channel) .addListener((Future<String> future) -> { if (future.isSuccess()) { if (RntbdHealthCheckResults.SuccessValue.equals(future.get())) { promise.setSuccess(Boolean.TRUE); } else { promise.setSuccess(Boolean.FALSE); } } else { promise.setFailure(future.cause()); } }); return promise; } /** * Determines whether a specified channel is healthy. * * @param channel A channel whose health is to be checked. * @return A future with a result reason {@link RntbdHealthCheckResults} if the channel is healthy, otherwise return the failed reason. */ public Future<String> isHealthyWithFailureReason(final Channel channel) { checkNotNull(channel, "expected non-null channel"); final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); final Promise<String> promise = channel.eventLoop().newPromise(); if (requestManager == null) { reportIssueUnless(logger, !channel.isActive(), channel, "active with no request manager"); return promise.setSuccess("active with no request manager"); } final Timestamps timestamps = requestManager.snapshotTimestamps(); final Instant currentTime = Instant.now(); if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() < recentReadWindowInNanos) { return promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } String writeIsHangMessage = this.isWriteHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(writeIsHangMessage)) { return promise.setSuccess(writeIsHangMessage); } String readIsHangMessage = this.isReadHang(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(readIsHangMessage)) { return promise.setSuccess(readIsHangMessage); } String transitTimeoutValidationMessage = this.transitTimeoutValidation(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(transitTimeoutValidationMessage)) { return promise.setSuccess(transitTimeoutValidationMessage); } String idleConnectionValidationMessage = this.idleConnectionValidation(timestamps, currentTime, channel); if(StringUtils.isNotEmpty(idleConnectionValidationMessage)) { return promise.setSuccess(idleConnectionValidationMessage); } String isCancellationProneChannelMessage = this.isCancellationProneChannel(timestamps, currentTime, requestManager, channel); if (StringUtils.isNotEmpty(isCancellationProneChannelMessage)) { return promise.setSuccess(isCancellationProneChannelMessage); } channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> { if (completed.isSuccess()) { promise.setSuccess(RntbdHealthCheckResults.SuccessValue); } else { String msg = MessageFormat.format( "{0} health check request failed due to: {1}", channel, completed.cause().toString() ); logger.warn(msg); promise.setSuccess(msg); } }); return promise; } private String isWriteHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long writeDelayInNanos = Duration.between(timestamps.lastChannelWriteTime(), timestamps.lastChannelWriteAttemptTime()).toNanos(); final long writeHangDurationInNanos = Duration.between(timestamps.lastChannelWriteAttemptTime(), currentTime).toNanos(); String writeHangMessage = StringUtils.EMPTY; if (writeDelayInNanos > this.writeDelayLimitInNanos && writeHangDurationInNanos > writeHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); writeHangMessage = MessageFormat.format( "{0} health check failed due to non-responding write: [lastChannelWriteAttemptTime: {1}, " + "lastChannelWriteTime: {2}, writeDelayInNanos: {3}, writeDelayLimitInNanos: {4}, " + "rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteAttemptTime(), timestamps.lastChannelWriteTime(), writeDelayInNanos, this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(writeHangMessage); } return writeHangMessage; } private String isReadHang(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { final long readDelay = Duration.between(timestamps.lastChannelReadTime(), timestamps.lastChannelWriteTime()).toNanos(); final long readHangDuration = Duration.between(timestamps.lastChannelWriteTime(), currentTime).toNanos(); String readHangMessage = StringUtils.EMPTY; if (readDelay > this.readDelayLimitInNanos && readHangDuration > readHangGracePeriodInNanos) { final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); readHangMessage = MessageFormat.format( "{0} health check failed due to non-responding read: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "readDelay: {3}, readDelayLimit: {4}, rntbdContext: {5}, pendingRequestCount: {6}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), readDelay, this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); logger.warn(readHangMessage); } return readHangMessage; } private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) { String transitTimeoutValidationMessage = StringUtils.EMPTY; if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) { if (CpuMemoryMonitor.getCpuLoad().isCpuOverThreshold(this.timeoutDetectionDisableCPUThreshold)) { return transitTimeoutValidationMessage; } final Optional<RntbdContext> rntbdContext = requestManager.rntbdContext(); long readDelay = Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos(); if (readDelay >= this.timeoutTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout detection time limit: [rntbdContext: {1}," + "lastChannelRead: {2}, timeoutTimeLimitInNanos: {3}]", channel, rntbdContext, timestamps.lastReadTime, this.timeoutTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.transitTimeoutCount() >= this.timeoutHighFrequencyThreshold && readDelay >= this.timeoutHighFrequencyTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout high frequency threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutCount: {3}, timeoutHighFrequencyThreshold: {4}, timeoutHighFrequencyTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutCount, this.timeoutHighFrequencyThreshold, this.timeoutHighFrequencyTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } if (timestamps.tansitTimeoutWriteCount() >= this.timeoutOnWriteThreshold && readDelay >= this.timeoutOnWriteTimeLimitInNanos) { transitTimeoutValidationMessage = MessageFormat.format( "{0} health check failed due to transit timeout on write threshold hit: [rntbdContext: {1}," + "lastChannelRead: {2}, transitTimeoutWriteCount: {3}, timeoutOnWriteThreshold: {4}, timeoutOnWriteTimeLimitInNanos: {5}]", channel, rntbdContext, timestamps.lastReadTime, timestamps.transitTimeoutWriteCount, this.timeoutOnWriteThreshold, this.timeoutOnWriteTimeLimitInNanos); logger.warn(transitTimeoutValidationMessage); return transitTimeoutValidationMessage; } } return transitTimeoutValidationMessage; } private String idleConnectionValidation(Timestamps timestamps, Instant currentTime, Channel channel) { String errorMessage = StringUtils.EMPTY; if (this.idleConnectionTimeoutInNanos > 0L) { if (Duration.between(timestamps.lastChannelReadTime(), currentTime).toNanos() > this.idleConnectionTimeoutInNanos) { errorMessage = MessageFormat.format( "{0} health check failed due to idle connection timeout: [lastChannelWrite: {1}, lastChannelRead: {2}, " + "idleConnectionTimeout: {3}, currentTime: {4}]", channel, timestamps.lastChannelWriteTime(), timestamps.lastChannelReadTime(), idleConnectionTimeoutInNanos, currentTime); logger.warn(errorMessage); } } return errorMessage; } @Override public String toString() { return RntbdObjectMapper.toString(this); } public static final class Timestamps { private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastPingUpdater = newUpdater(Timestamps.class, Instant.class, "lastPingTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant>lastReadUpdater = newUpdater(Timestamps.class, Instant.class, "lastReadTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteTime"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> lastWriteAttemptUpdater = newUpdater(Timestamps.class, Instant.class, "lastWriteAttemptTime"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutCount"); private static final AtomicIntegerFieldUpdater<Timestamps> transitTimeoutWriteCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "transitTimeoutWriteCount"); private static final AtomicReferenceFieldUpdater<Timestamps, Instant> transitTimeoutStartingTimeUpdater = newUpdater(Timestamps.class, Instant.class, "transitTimeoutStartingTime"); private static final AtomicIntegerFieldUpdater<Timestamps> cancellationCountUpdater = AtomicIntegerFieldUpdater.newUpdater(Timestamps.class, "cancellationCount"); private volatile Instant lastPingTime; private volatile Instant lastReadTime; private volatile Instant lastWriteTime; private volatile Instant lastWriteAttemptTime; private volatile int transitTimeoutCount; private volatile int transitTimeoutWriteCount; private volatile Instant transitTimeoutStartingTime; private volatile int cancellationCount; public Timestamps() { lastPingUpdater.set(this, Instant.now()); lastReadUpdater.set(this, Instant.now()); lastWriteUpdater.set(this, Instant.now()); lastWriteAttemptUpdater.set(this, Instant.now()); } @SuppressWarnings("CopyConstructorMissesField") public Timestamps(Timestamps other) { checkNotNull(other, "other: null"); this.lastPingTime = lastPingUpdater.get(other); this.lastReadTime = lastReadUpdater.get(other); this.lastWriteTime = lastWriteUpdater.get(other); this.lastWriteAttemptTime = lastWriteAttemptUpdater.get(other); this.transitTimeoutCount = transitTimeoutCountUpdater.get(other); this.transitTimeoutWriteCount = transitTimeoutWriteCountUpdater.get(other); this.transitTimeoutStartingTime = transitTimeoutStartingTimeUpdater.get(other); this.cancellationCount = cancellationCountUpdater.get(other); } public void channelPingCompleted() { lastPingUpdater.set(this, Instant.now()); } public void channelReadCompleted() { lastReadUpdater.set(this, Instant.now()); this.resetTransitTimeout(); this.resetCancellationCount(); } public void channelWriteAttempted() { lastWriteAttemptUpdater.set(this, Instant.now()); } public void channelWriteCompleted() { lastWriteUpdater.set(this, Instant.now()); } public void transitTimeout(boolean isReadOnly, Instant requestCreatedTime) { if (transitTimeoutCountUpdater.incrementAndGet(this) == 1) { transitTimeoutStartingTimeUpdater.set(this, requestCreatedTime); } if (!isReadOnly) { transitTimeoutWriteCountUpdater.incrementAndGet(this); } } public void resetTransitTimeout() { transitTimeoutCountUpdater.set(this, 0); transitTimeoutWriteCountUpdater.set(this, 0); transitTimeoutStartingTimeUpdater.set(this, null); } public void resetCancellationCount() { cancellationCountUpdater.set(this, 0); } @JsonProperty public Instant lastChannelPingTime() { return lastPingUpdater.get(this); } @JsonProperty public Instant lastChannelReadTime() { return lastReadUpdater.get(this); } @JsonProperty public Instant lastChannelWriteTime() { return lastWriteUpdater.get(this); } @JsonProperty public Instant lastChannelWriteAttemptTime() { return lastWriteAttemptUpdater.get(this); } @JsonProperty public int transitTimeoutCount() { return transitTimeoutCountUpdater.get(this); } @JsonProperty public int tansitTimeoutWriteCount() { return transitTimeoutWriteCountUpdater.get(this); } @JsonProperty public Instant transitTimeoutStartingTime() { return transitTimeoutStartingTimeUpdater.get(this); } @JsonProperty public int cancellationCount() { return cancellationCountUpdater.get(this); } @JsonProperty public void cancellation() { cancellationCountUpdater.incrementAndGet(this); } @Override public String toString() { return RntbdObjectMapper.toString(this); } } }
I don't think you need to code it there. Just do a register would be OK. And we probably still need to track what namespace we registered on Test subscription.
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); managedNetworkFabricManager = ManagedNetworkFabricManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String registrationState = resourceManager.providers() .getByName("Microsoft.ManagedNetworkFabric").registrationState(); if ("NotRegistered".equalsIgnoreCase(registrationState) || "Unregistered".equalsIgnoreCase(registrationState)) { resourceManager.providers().register("Microsoft.ManagedNetworkFabric"); registrationState = resourceManager.providers() .getByName("Microsoft.ManagedNetworkFabric").registrationState(); while (!"Registered".equalsIgnoreCase(registrationState)) { ResourceManagerUtils.sleep(Duration.ofSeconds(10L)); registrationState = resourceManager.providers() .getByName("Microsoft.ManagedNetworkFabric").registrationState(); } } String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(REGION) .create(); } }
}
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); managedNetworkFabricManager = ManagedNetworkFabricManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(REGION) .create(); } }
class ManagedNetworkFabricManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST; private String resourceGroupName = "rg" + randomPadding(); private ManagedNetworkFabricManager managedNetworkFabricManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateAccessController() { AccessControlList acl = null; String randomPadding = randomPadding(); try { String aclName = "acl" + randomPadding; String matchName = "match" + randomPadding; String vlgName = "vlg" + randomPadding; String ipgName = "ipg" + randomPadding; String pgName = "pg" + randomPadding; String counterName = "counter" + randomPadding; acl = managedNetworkFabricManager .accessControlLists() .define(aclName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withConfigurationType(ConfigurationType.FILE) .withMatchConfigurations( Collections.singletonList( new AccessControlListMatchConfiguration() .withMatchConfigurationName(matchName) .withSequenceNumber(123L) .withIpAddressType(IpAddressType.IPV4) .withMatchConditions( Collections.singletonList( new AccessControlListMatchCondition() .withProtocolTypes(Collections.singletonList("TCP")) .withVlanMatchCondition( new VlanMatchCondition() .withVlans(Collections.singletonList("20-30")) .withInnerVlans(Collections.singletonList("30")) .withVlanGroupNames(Collections.singletonList(vlgName))) .withIpCondition( new IpMatchCondition() .withType(SourceDestinationType.SOURCE_IP) .withPrefixType(PrefixType.PREFIX) .withIpPrefixValues(Collections.singletonList("10.20.20.20/12")) .withIpGroupNames(Collections.singletonList(ipgName))) .withEtherTypes(Collections.singletonList("0x1")) .withFragments(Collections.singletonList("0xff00-0xffff")) .withIpLengths(Collections.singletonList("4094-9214")) .withTtlValues(Collections.singletonList("23")) .withDscpMarkings(Collections.singletonList("32")) .withPortCondition( new AccessControlListPortCondition() .withPortType(PortType.SOURCE_PORT) .withLayer4Protocol(Layer4Protocol.TCP) .withPorts(Collections.singletonList("1-20")) .withPortGroupNames(Collections.singletonList(pgName)) .withFlags(Collections.singletonList("established"))))) .withActions( Collections.singletonList( new AccessControlListAction() .withType(AclActionType.COUNT) .withCounterName(counterName))))) .withDynamicMatchConfigurations( Collections.singletonList( new CommonDynamicMatchConfiguration() .withIpGroups( Collections.singletonList( new IpGroupProperties() .withName(ipgName) .withIpAddressType(IpAddressType.IPV4) .withIpPrefixes(Collections.singletonList("10.20.3.1/20")))) .withVlanGroups( Collections.singletonList( new VlanGroupProperties() .withName(vlgName) .withVlans(Collections.singletonList("20-30")))) .withPortGroups( Collections.singletonList( new PortGroupProperties() .withName(pgName) .withPorts(Collections.singletonList("100-200")))))) .withAnnotation("annotation") .create(); acl.refresh(); Assertions.assertEquals(acl.name(), aclName); Assertions.assertEquals(acl.name(), managedNetworkFabricManager.accessControlLists().getById(acl.id()).name()); Assertions.assertTrue(managedNetworkFabricManager.accessControlLists().list().stream().findAny().isPresent()); } finally { if (acl != null) { managedNetworkFabricManager.accessControlLists().deleteById(acl.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class ManagedNetworkFabricManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST; private String resourceGroupName = "rg" + randomPadding(); private ManagedNetworkFabricManager managedNetworkFabricManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateAccessController() { AccessControlList acl = null; String randomPadding = randomPadding(); try { String aclName = "acl" + randomPadding; String matchName = "match" + randomPadding; String vlgName = "vlg" + randomPadding; String ipgName = "ipg" + randomPadding; String pgName = "pg" + randomPadding; String counterName = "counter" + randomPadding; acl = managedNetworkFabricManager .accessControlLists() .define(aclName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withConfigurationType(ConfigurationType.FILE) .withMatchConfigurations( Collections.singletonList( new AccessControlListMatchConfiguration() .withMatchConfigurationName(matchName) .withSequenceNumber(123L) .withIpAddressType(IpAddressType.IPV4) .withMatchConditions( Collections.singletonList( new AccessControlListMatchCondition() .withProtocolTypes(Collections.singletonList("TCP")) .withVlanMatchCondition( new VlanMatchCondition() .withVlans(Collections.singletonList("20-30")) .withInnerVlans(Collections.singletonList("30")) .withVlanGroupNames(Collections.singletonList(vlgName))) .withIpCondition( new IpMatchCondition() .withType(SourceDestinationType.SOURCE_IP) .withPrefixType(PrefixType.PREFIX) .withIpPrefixValues(Collections.singletonList("10.20.20.20/12")) .withIpGroupNames(Collections.singletonList(ipgName))) .withEtherTypes(Collections.singletonList("0x1")) .withFragments(Collections.singletonList("0xff00-0xffff")) .withIpLengths(Collections.singletonList("4094-9214")) .withTtlValues(Collections.singletonList("23")) .withDscpMarkings(Collections.singletonList("32")) .withPortCondition( new AccessControlListPortCondition() .withPortType(PortType.SOURCE_PORT) .withLayer4Protocol(Layer4Protocol.TCP) .withPorts(Collections.singletonList("1-20")) .withPortGroupNames(Collections.singletonList(pgName)) .withFlags(Collections.singletonList("established"))))) .withActions( Collections.singletonList( new AccessControlListAction() .withType(AclActionType.COUNT) .withCounterName(counterName))))) .withDynamicMatchConfigurations( Collections.singletonList( new CommonDynamicMatchConfiguration() .withIpGroups( Collections.singletonList( new IpGroupProperties() .withName(ipgName) .withIpAddressType(IpAddressType.IPV4) .withIpPrefixes(Collections.singletonList("10.20.3.1/20")))) .withVlanGroups( Collections.singletonList( new VlanGroupProperties() .withName(vlgName) .withVlans(Collections.singletonList("20-30")))) .withPortGroups( Collections.singletonList( new PortGroupProperties() .withName(pgName) .withPorts(Collections.singletonList("100-200")))))) .withAnnotation("annotation") .create(); acl.refresh(); Assertions.assertEquals(acl.name(), aclName); Assertions.assertEquals(acl.name(), managedNetworkFabricManager.accessControlLists().getById(acl.id()).name()); Assertions.assertTrue(managedNetworkFabricManager.accessControlLists().list().stream().findAny().isPresent()); } finally { if (acl != null) { managedNetworkFabricManager.accessControlLists().deleteById(acl.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
An exception such as `The subscription registration is in 'Unregistered' state. The subscription must be registered to use namespace 'Microsoft.ManagedNetworkFabric'` occurred during the pipeline live test, because I can not register the provider on test subscription through the `azure portal` , so added this code snippet. Now this `Microsoft.ManagedNetworkFabric` has been registered, there will be no problem removed this code snippet.
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); managedNetworkFabricManager = ManagedNetworkFabricManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String registrationState = resourceManager.providers() .getByName("Microsoft.ManagedNetworkFabric").registrationState(); if ("NotRegistered".equalsIgnoreCase(registrationState) || "Unregistered".equalsIgnoreCase(registrationState)) { resourceManager.providers().register("Microsoft.ManagedNetworkFabric"); registrationState = resourceManager.providers() .getByName("Microsoft.ManagedNetworkFabric").registrationState(); while (!"Registered".equalsIgnoreCase(registrationState)) { ResourceManagerUtils.sleep(Duration.ofSeconds(10L)); registrationState = resourceManager.providers() .getByName("Microsoft.ManagedNetworkFabric").registrationState(); } } String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(REGION) .create(); } }
}
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); managedNetworkFabricManager = ManagedNetworkFabricManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(REGION) .create(); } }
class ManagedNetworkFabricManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST; private String resourceGroupName = "rg" + randomPadding(); private ManagedNetworkFabricManager managedNetworkFabricManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateAccessController() { AccessControlList acl = null; String randomPadding = randomPadding(); try { String aclName = "acl" + randomPadding; String matchName = "match" + randomPadding; String vlgName = "vlg" + randomPadding; String ipgName = "ipg" + randomPadding; String pgName = "pg" + randomPadding; String counterName = "counter" + randomPadding; acl = managedNetworkFabricManager .accessControlLists() .define(aclName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withConfigurationType(ConfigurationType.FILE) .withMatchConfigurations( Collections.singletonList( new AccessControlListMatchConfiguration() .withMatchConfigurationName(matchName) .withSequenceNumber(123L) .withIpAddressType(IpAddressType.IPV4) .withMatchConditions( Collections.singletonList( new AccessControlListMatchCondition() .withProtocolTypes(Collections.singletonList("TCP")) .withVlanMatchCondition( new VlanMatchCondition() .withVlans(Collections.singletonList("20-30")) .withInnerVlans(Collections.singletonList("30")) .withVlanGroupNames(Collections.singletonList(vlgName))) .withIpCondition( new IpMatchCondition() .withType(SourceDestinationType.SOURCE_IP) .withPrefixType(PrefixType.PREFIX) .withIpPrefixValues(Collections.singletonList("10.20.20.20/12")) .withIpGroupNames(Collections.singletonList(ipgName))) .withEtherTypes(Collections.singletonList("0x1")) .withFragments(Collections.singletonList("0xff00-0xffff")) .withIpLengths(Collections.singletonList("4094-9214")) .withTtlValues(Collections.singletonList("23")) .withDscpMarkings(Collections.singletonList("32")) .withPortCondition( new AccessControlListPortCondition() .withPortType(PortType.SOURCE_PORT) .withLayer4Protocol(Layer4Protocol.TCP) .withPorts(Collections.singletonList("1-20")) .withPortGroupNames(Collections.singletonList(pgName)) .withFlags(Collections.singletonList("established"))))) .withActions( Collections.singletonList( new AccessControlListAction() .withType(AclActionType.COUNT) .withCounterName(counterName))))) .withDynamicMatchConfigurations( Collections.singletonList( new CommonDynamicMatchConfiguration() .withIpGroups( Collections.singletonList( new IpGroupProperties() .withName(ipgName) .withIpAddressType(IpAddressType.IPV4) .withIpPrefixes(Collections.singletonList("10.20.3.1/20")))) .withVlanGroups( Collections.singletonList( new VlanGroupProperties() .withName(vlgName) .withVlans(Collections.singletonList("20-30")))) .withPortGroups( Collections.singletonList( new PortGroupProperties() .withName(pgName) .withPorts(Collections.singletonList("100-200")))))) .withAnnotation("annotation") .create(); acl.refresh(); Assertions.assertEquals(acl.name(), aclName); Assertions.assertEquals(acl.name(), managedNetworkFabricManager.accessControlLists().getById(acl.id()).name()); Assertions.assertTrue(managedNetworkFabricManager.accessControlLists().list().stream().findAny().isPresent()); } finally { if (acl != null) { managedNetworkFabricManager.accessControlLists().deleteById(acl.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class ManagedNetworkFabricManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST; private String resourceGroupName = "rg" + randomPadding(); private ManagedNetworkFabricManager managedNetworkFabricManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateAccessController() { AccessControlList acl = null; String randomPadding = randomPadding(); try { String aclName = "acl" + randomPadding; String matchName = "match" + randomPadding; String vlgName = "vlg" + randomPadding; String ipgName = "ipg" + randomPadding; String pgName = "pg" + randomPadding; String counterName = "counter" + randomPadding; acl = managedNetworkFabricManager .accessControlLists() .define(aclName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withConfigurationType(ConfigurationType.FILE) .withMatchConfigurations( Collections.singletonList( new AccessControlListMatchConfiguration() .withMatchConfigurationName(matchName) .withSequenceNumber(123L) .withIpAddressType(IpAddressType.IPV4) .withMatchConditions( Collections.singletonList( new AccessControlListMatchCondition() .withProtocolTypes(Collections.singletonList("TCP")) .withVlanMatchCondition( new VlanMatchCondition() .withVlans(Collections.singletonList("20-30")) .withInnerVlans(Collections.singletonList("30")) .withVlanGroupNames(Collections.singletonList(vlgName))) .withIpCondition( new IpMatchCondition() .withType(SourceDestinationType.SOURCE_IP) .withPrefixType(PrefixType.PREFIX) .withIpPrefixValues(Collections.singletonList("10.20.20.20/12")) .withIpGroupNames(Collections.singletonList(ipgName))) .withEtherTypes(Collections.singletonList("0x1")) .withFragments(Collections.singletonList("0xff00-0xffff")) .withIpLengths(Collections.singletonList("4094-9214")) .withTtlValues(Collections.singletonList("23")) .withDscpMarkings(Collections.singletonList("32")) .withPortCondition( new AccessControlListPortCondition() .withPortType(PortType.SOURCE_PORT) .withLayer4Protocol(Layer4Protocol.TCP) .withPorts(Collections.singletonList("1-20")) .withPortGroupNames(Collections.singletonList(pgName)) .withFlags(Collections.singletonList("established"))))) .withActions( Collections.singletonList( new AccessControlListAction() .withType(AclActionType.COUNT) .withCounterName(counterName))))) .withDynamicMatchConfigurations( Collections.singletonList( new CommonDynamicMatchConfiguration() .withIpGroups( Collections.singletonList( new IpGroupProperties() .withName(ipgName) .withIpAddressType(IpAddressType.IPV4) .withIpPrefixes(Collections.singletonList("10.20.3.1/20")))) .withVlanGroups( Collections.singletonList( new VlanGroupProperties() .withName(vlgName) .withVlans(Collections.singletonList("20-30")))) .withPortGroups( Collections.singletonList( new PortGroupProperties() .withName(pgName) .withPorts(Collections.singletonList("100-200")))))) .withAnnotation("annotation") .create(); acl.refresh(); Assertions.assertEquals(acl.name(), aclName); Assertions.assertEquals(acl.name(), managedNetworkFabricManager.accessControlLists().getById(acl.id()).name()); Assertions.assertTrue(managedNetworkFabricManager.accessControlLists().list().stream().findAny().isPresent()); } finally { if (acl != null) { managedNetworkFabricManager.accessControlLists().deleteById(acl.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Got it. That's fine. I wasn't aware that the AAD via script actually have the permission to register namespace (ideally it should be one with low permission limited to the resource group...). In future, maybe just tell us so we do it manually (or maybe have a script to do similar).
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); managedNetworkFabricManager = ManagedNetworkFabricManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String registrationState = resourceManager.providers() .getByName("Microsoft.ManagedNetworkFabric").registrationState(); if ("NotRegistered".equalsIgnoreCase(registrationState) || "Unregistered".equalsIgnoreCase(registrationState)) { resourceManager.providers().register("Microsoft.ManagedNetworkFabric"); registrationState = resourceManager.providers() .getByName("Microsoft.ManagedNetworkFabric").registrationState(); while (!"Registered".equalsIgnoreCase(registrationState)) { ResourceManagerUtils.sleep(Duration.ofSeconds(10L)); registrationState = resourceManager.providers() .getByName("Microsoft.ManagedNetworkFabric").registrationState(); } } String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(REGION) .create(); } }
}
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); managedNetworkFabricManager = ManagedNetworkFabricManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(REGION) .create(); } }
class ManagedNetworkFabricManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST; private String resourceGroupName = "rg" + randomPadding(); private ManagedNetworkFabricManager managedNetworkFabricManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateAccessController() { AccessControlList acl = null; String randomPadding = randomPadding(); try { String aclName = "acl" + randomPadding; String matchName = "match" + randomPadding; String vlgName = "vlg" + randomPadding; String ipgName = "ipg" + randomPadding; String pgName = "pg" + randomPadding; String counterName = "counter" + randomPadding; acl = managedNetworkFabricManager .accessControlLists() .define(aclName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withConfigurationType(ConfigurationType.FILE) .withMatchConfigurations( Collections.singletonList( new AccessControlListMatchConfiguration() .withMatchConfigurationName(matchName) .withSequenceNumber(123L) .withIpAddressType(IpAddressType.IPV4) .withMatchConditions( Collections.singletonList( new AccessControlListMatchCondition() .withProtocolTypes(Collections.singletonList("TCP")) .withVlanMatchCondition( new VlanMatchCondition() .withVlans(Collections.singletonList("20-30")) .withInnerVlans(Collections.singletonList("30")) .withVlanGroupNames(Collections.singletonList(vlgName))) .withIpCondition( new IpMatchCondition() .withType(SourceDestinationType.SOURCE_IP) .withPrefixType(PrefixType.PREFIX) .withIpPrefixValues(Collections.singletonList("10.20.20.20/12")) .withIpGroupNames(Collections.singletonList(ipgName))) .withEtherTypes(Collections.singletonList("0x1")) .withFragments(Collections.singletonList("0xff00-0xffff")) .withIpLengths(Collections.singletonList("4094-9214")) .withTtlValues(Collections.singletonList("23")) .withDscpMarkings(Collections.singletonList("32")) .withPortCondition( new AccessControlListPortCondition() .withPortType(PortType.SOURCE_PORT) .withLayer4Protocol(Layer4Protocol.TCP) .withPorts(Collections.singletonList("1-20")) .withPortGroupNames(Collections.singletonList(pgName)) .withFlags(Collections.singletonList("established"))))) .withActions( Collections.singletonList( new AccessControlListAction() .withType(AclActionType.COUNT) .withCounterName(counterName))))) .withDynamicMatchConfigurations( Collections.singletonList( new CommonDynamicMatchConfiguration() .withIpGroups( Collections.singletonList( new IpGroupProperties() .withName(ipgName) .withIpAddressType(IpAddressType.IPV4) .withIpPrefixes(Collections.singletonList("10.20.3.1/20")))) .withVlanGroups( Collections.singletonList( new VlanGroupProperties() .withName(vlgName) .withVlans(Collections.singletonList("20-30")))) .withPortGroups( Collections.singletonList( new PortGroupProperties() .withName(pgName) .withPorts(Collections.singletonList("100-200")))))) .withAnnotation("annotation") .create(); acl.refresh(); Assertions.assertEquals(acl.name(), aclName); Assertions.assertEquals(acl.name(), managedNetworkFabricManager.accessControlLists().getById(acl.id()).name()); Assertions.assertTrue(managedNetworkFabricManager.accessControlLists().list().stream().findAny().isPresent()); } finally { if (acl != null) { managedNetworkFabricManager.accessControlLists().deleteById(acl.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class ManagedNetworkFabricManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST; private String resourceGroupName = "rg" + randomPadding(); private ManagedNetworkFabricManager managedNetworkFabricManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateAccessController() { AccessControlList acl = null; String randomPadding = randomPadding(); try { String aclName = "acl" + randomPadding; String matchName = "match" + randomPadding; String vlgName = "vlg" + randomPadding; String ipgName = "ipg" + randomPadding; String pgName = "pg" + randomPadding; String counterName = "counter" + randomPadding; acl = managedNetworkFabricManager .accessControlLists() .define(aclName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withConfigurationType(ConfigurationType.FILE) .withMatchConfigurations( Collections.singletonList( new AccessControlListMatchConfiguration() .withMatchConfigurationName(matchName) .withSequenceNumber(123L) .withIpAddressType(IpAddressType.IPV4) .withMatchConditions( Collections.singletonList( new AccessControlListMatchCondition() .withProtocolTypes(Collections.singletonList("TCP")) .withVlanMatchCondition( new VlanMatchCondition() .withVlans(Collections.singletonList("20-30")) .withInnerVlans(Collections.singletonList("30")) .withVlanGroupNames(Collections.singletonList(vlgName))) .withIpCondition( new IpMatchCondition() .withType(SourceDestinationType.SOURCE_IP) .withPrefixType(PrefixType.PREFIX) .withIpPrefixValues(Collections.singletonList("10.20.20.20/12")) .withIpGroupNames(Collections.singletonList(ipgName))) .withEtherTypes(Collections.singletonList("0x1")) .withFragments(Collections.singletonList("0xff00-0xffff")) .withIpLengths(Collections.singletonList("4094-9214")) .withTtlValues(Collections.singletonList("23")) .withDscpMarkings(Collections.singletonList("32")) .withPortCondition( new AccessControlListPortCondition() .withPortType(PortType.SOURCE_PORT) .withLayer4Protocol(Layer4Protocol.TCP) .withPorts(Collections.singletonList("1-20")) .withPortGroupNames(Collections.singletonList(pgName)) .withFlags(Collections.singletonList("established"))))) .withActions( Collections.singletonList( new AccessControlListAction() .withType(AclActionType.COUNT) .withCounterName(counterName))))) .withDynamicMatchConfigurations( Collections.singletonList( new CommonDynamicMatchConfiguration() .withIpGroups( Collections.singletonList( new IpGroupProperties() .withName(ipgName) .withIpAddressType(IpAddressType.IPV4) .withIpPrefixes(Collections.singletonList("10.20.3.1/20")))) .withVlanGroups( Collections.singletonList( new VlanGroupProperties() .withName(vlgName) .withVlans(Collections.singletonList("20-30")))) .withPortGroups( Collections.singletonList( new PortGroupProperties() .withName(pgName) .withPorts(Collections.singletonList("100-200")))))) .withAnnotation("annotation") .create(); acl.refresh(); Assertions.assertEquals(acl.name(), aclName); Assertions.assertEquals(acl.name(), managedNetworkFabricManager.accessControlLists().getById(acl.id()).name()); Assertions.assertTrue(managedNetworkFabricManager.accessControlLists().list().stream().findAny().isPresent()); } finally { if (acl != null) { managedNetworkFabricManager.accessControlLists().deleteById(acl.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Add missing > in placeholder
public void tsgEnableHttpLogging() { DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient logsIngestionClient = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint") .credential(credential) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .buildClient(); }
.endpoint("<data-collection-endpoint")
public void tsgEnableHttpLogging() { DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient logsIngestionClient = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(credential) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .buildClient(); }
class ReadmeSamples { /** * Sample to demonstrate creation of a synchronous client. */ public void createClient() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(tokenCredential) .buildClient(); } /** * Sample to demonstrate creation of an asynchronous client. */ public void createAsyncClient() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionAsyncClient asyncClient = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(tokenCredential) .buildAsyncClient(); } /** * Sample to demonstrate uploading logs to Azure Monitor. */ public void uploadLogs() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint") .credential(tokenCredential) .buildClient(); List<Object> logs = getLogs(); client.upload("<data-collection-rule-id>", "<stream-name>", logs); System.out.println("Logs uploaded successfully"); } /** * Sample to demonstrate uploading logs to Azure Monitor. */ public void uploadLogsWithMaxConcurrency() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint") .credential(tokenCredential) .buildClient(); List<Object> logs = getLogs(); LogsUploadOptions logsUploadOptions = new LogsUploadOptions() .setMaxConcurrency(3); client.upload("<data-collection-rule-id>", "<stream-name>", logs, logsUploadOptions, Context.NONE); System.out.println("Logs uploaded successfully"); } /** * Sample to demonstrate uploading logs to Azure Monitor. */ public void uploadLogsWithErrorHandler() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint") .credential(tokenCredential) .buildClient(); List<Object> logs = getLogs(); LogsUploadOptions logsUploadOptions = new LogsUploadOptions() .setLogsUploadErrorConsumer(uploadLogsError -> { System.out.println("Error message " + uploadLogsError.getResponseException().getMessage()); System.out.println("Total logs failed to upload = " + uploadLogsError.getFailedLogs().size()); }); client.upload("<data-collection-rule-id>", "<stream-name>", logs, logsUploadOptions, Context.NONE); } /** * Enable HTTP request and response logging. */ private List<Object> getLogs() { return null; } }
class ReadmeSamples { /** * Sample to demonstrate creation of a synchronous client. */ public void createClient() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(tokenCredential) .buildClient(); } /** * Sample to demonstrate creation of an asynchronous client. */ public void createAsyncClient() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionAsyncClient asyncClient = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(tokenCredential) .buildAsyncClient(); } /** * Sample to demonstrate uploading logs to Azure Monitor. */ public void uploadLogs() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(tokenCredential) .buildClient(); List<Object> logs = getLogs(); client.upload("<data-collection-rule-id>", "<stream-name>", logs); System.out.println("Logs uploaded successfully"); } /** * Sample to demonstrate uploading logs to Azure Monitor. */ public void uploadLogsWithMaxConcurrency() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(tokenCredential) .buildClient(); List<Object> logs = getLogs(); LogsUploadOptions logsUploadOptions = new LogsUploadOptions() .setMaxConcurrency(3); client.upload("<data-collection-rule-id>", "<stream-name>", logs, logsUploadOptions, Context.NONE); System.out.println("Logs uploaded successfully"); } /** * Sample to demonstrate uploading logs to Azure Monitor. */ public void uploadLogsWithErrorHandler() { DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); LogsIngestionClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(tokenCredential) .buildClient(); List<Object> logs = getLogs(); LogsUploadOptions logsUploadOptions = new LogsUploadOptions() .setLogsUploadErrorConsumer(uploadLogsError -> { System.out.println("Error message " + uploadLogsError.getResponseException().getMessage()); System.out.println("Total logs failed to upload = " + uploadLogsError.getFailedLogs().size()); }); client.upload("<data-collection-rule-id>", "<stream-name>", logs, logsUploadOptions, Context.NONE); } /** * Enable HTTP request and response logging. */ private List<Object> getLogs() { return null; } }
We might need to keep this to avoid authentication failing. If you find it's not necessary, dismiss this comment.
void setSecretRunner(Consumer<KeyVaultSecret> testRunner) { final Map<String, String> tags = Collections.singletonMap("foo", "baz"); String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags) .setContentType("text")); testRunner.accept(secretToSet); }
final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE)
void setSecretRunner(Consumer<KeyVaultSecret> testRunner) { final Map<String, String> tags = Collections.singletonMap("foo", "baz"); String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags) .setContentType("text")); testRunner.accept(secretToSet); }
class SecretClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_SECRETS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS); private static final String SECRET_NAME = "javaSecretTemp"; private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; private static final int MAX_RETRIES = 5; private static final RetryOptions LIVE_RETRY_OPTIONS = new RetryOptions(new ExponentialBackoffOptions() .setMaxRetries(MAX_RETRIES) .setBaseDelay(Duration.ofSeconds(2)) .setMaxDelay(Duration.ofSeconds(16))); private static final RetryOptions PLAYBACK_RETRY_OPTIONS = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); } SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, SecretServiceVersion serviceVersion) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } SecretClientBuilder builder = new SecretClientBuilder() .vaultUrl(endpoint) .serviceVersion(serviceVersion) .credential(credential) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); return interceptorManager.isRecordMode() ? builder.addPolicy(interceptorManager.getRecordPolicy()) : builder; } } @Test public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion); void setSecretEmptyValueRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, ""); testRunner.accept(secretToSet); } @Test public abstract void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); String resourceId = testResourceNamer.randomName("testSecretUpdate", 20); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateDisabledSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testUpdateOfDisabledSecret", 35); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGet", 20); final KeyVaultSecret secretToGet = new KeyVaultSecret(resourceId, "testSecretGetVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToGet); } @Test public abstract void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretSpecificVersionRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetVersion", 30); final KeyVaultSecret secretWithOriginalValue = new KeyVaultSecret(resourceId, "testSecretGetVersionVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); final KeyVaultSecret secretWithNewValue = new KeyVaultSecret(resourceId, "newVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretWithOriginalValue, secretWithNewValue); } @Test public abstract void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void deleteSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretDelete", 20); final KeyVaultSecret secretToDelete = new KeyVaultSecret(resourceId, "testSecretDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDelete); } @Test public abstract void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetDeleted", 25); final KeyVaultSecret secretToDeleteAndGet = new KeyVaultSecret(resourceId, "testSecretGetDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndGet); } @Test public abstract void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void recoverDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretRecover", 25); final KeyVaultSecret secretToDeleteAndRecover = new KeyVaultSecret(resourceId, "testSecretRecoverVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndRecover); } @Test public abstract void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void backupSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackup = new KeyVaultSecret(testResourceNamer.randomName("testSecretBackup", 20), "testSecretBackupVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackup); } @Test public abstract void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void restoreSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackupAndRestore = new KeyVaultSecret(testResourceNamer.randomName("testSecretRestore", 20), "testSecretRestoreVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2080, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackupAndRestore); } @Test public abstract void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretsToSetAndList = new HashMap<>(); for (int i = 0; i < 2; i++) { String secretName = testResourceNamer.randomName("listSecret", 20); String secretVal = "listSecretVal" + i; KeyVaultSecret secret = new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); secretsToSetAndList.put(secretName, secret); } testRunner.accept(secretsToSetAndList); } @Test public abstract void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listDeletedSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretSecretsToSetAndDelete = new HashMap<>(); for (int i = 0; i < 3; i++) { String secretName = testResourceNamer.randomName("listDeletedSecretsTest", 20); String secretVal = "listDeletedSecretVal" + i; secretSecretsToSetAndDelete.put(secretName, new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretSecretsToSetAndDelete); } @Test public abstract void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretVersionsRunner(Consumer<List<KeyVaultSecret>> testRunner) { List<KeyVaultSecret> secretsToSetAndList = new ArrayList<>(); String secretVal; String secretName = testResourceNamer.randomName("listSecretVersion", 20); for (int i = 1; i < 5; i++) { secretVal = "listSecretVersionVal" + i; secretsToSetAndList.add(new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretsToSetAndList); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting contained in the RestResponse body. */ static void assertSecretEquals(KeyVaultSecret expected, KeyVaultSecret actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getProperties().getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getProperties().getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertRestException(assertThrows(expectedExceptionType, exceptionThrower::run), expectedExceptionType, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(SecretServiceVersion.values()).filter(SecretClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link SecretServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return SecretServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
class SecretClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_SECRETS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS); private static final String SECRET_NAME = "javaSecretTemp"; private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; private static final int MAX_RETRIES = 5; private static final RetryOptions LIVE_RETRY_OPTIONS = new RetryOptions(new ExponentialBackoffOptions() .setMaxRetries(MAX_RETRIES) .setBaseDelay(Duration.ofSeconds(2)) .setMaxDelay(Duration.ofSeconds(16))); private static final RetryOptions PLAYBACK_RETRY_OPTIONS = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); } SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, SecretServiceVersion serviceVersion) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } SecretClientBuilder builder = new SecretClientBuilder() .vaultUrl(endpoint) .serviceVersion(serviceVersion) .credential(credential) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); return interceptorManager.isRecordMode() ? builder.addPolicy(interceptorManager.getRecordPolicy()) : builder; } } @Test public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion); void setSecretEmptyValueRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, ""); testRunner.accept(secretToSet); } @Test public abstract void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); String resourceId = testResourceNamer.randomName("testSecretUpdate", 20); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateDisabledSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testUpdateOfDisabledSecret", 35); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGet", 20); final KeyVaultSecret secretToGet = new KeyVaultSecret(resourceId, "testSecretGetVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToGet); } @Test public abstract void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretSpecificVersionRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetVersion", 30); final KeyVaultSecret secretWithOriginalValue = new KeyVaultSecret(resourceId, "testSecretGetVersionVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); final KeyVaultSecret secretWithNewValue = new KeyVaultSecret(resourceId, "newVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretWithOriginalValue, secretWithNewValue); } @Test public abstract void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void deleteSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretDelete", 20); final KeyVaultSecret secretToDelete = new KeyVaultSecret(resourceId, "testSecretDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDelete); } @Test public abstract void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetDeleted", 25); final KeyVaultSecret secretToDeleteAndGet = new KeyVaultSecret(resourceId, "testSecretGetDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndGet); } @Test public abstract void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void recoverDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretRecover", 25); final KeyVaultSecret secretToDeleteAndRecover = new KeyVaultSecret(resourceId, "testSecretRecoverVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndRecover); } @Test public abstract void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void backupSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackup = new KeyVaultSecret(testResourceNamer.randomName("testSecretBackup", 20), "testSecretBackupVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackup); } @Test public abstract void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void restoreSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackupAndRestore = new KeyVaultSecret(testResourceNamer.randomName("testSecretRestore", 20), "testSecretRestoreVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2080, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackupAndRestore); } @Test public abstract void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretsToSetAndList = new HashMap<>(); for (int i = 0; i < 2; i++) { String secretName = testResourceNamer.randomName("listSecret", 20); String secretVal = "listSecretVal" + i; KeyVaultSecret secret = new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); secretsToSetAndList.put(secretName, secret); } testRunner.accept(secretsToSetAndList); } @Test public abstract void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listDeletedSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretSecretsToSetAndDelete = new HashMap<>(); for (int i = 0; i < 3; i++) { String secretName = testResourceNamer.randomName("listDeletedSecretsTest", 20); String secretVal = "listDeletedSecretVal" + i; secretSecretsToSetAndDelete.put(secretName, new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretSecretsToSetAndDelete); } @Test public abstract void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretVersionsRunner(Consumer<List<KeyVaultSecret>> testRunner) { List<KeyVaultSecret> secretsToSetAndList = new ArrayList<>(); String secretVal; String secretName = testResourceNamer.randomName("listSecretVersion", 20); for (int i = 1; i < 5; i++) { secretVal = "listSecretVersionVal" + i; secretsToSetAndList.add(new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretsToSetAndList); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting contained in the RestResponse body. */ static void assertSecretEquals(KeyVaultSecret expected, KeyVaultSecret actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getProperties().getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getProperties().getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertRestException(assertThrows(expectedExceptionType, exceptionThrower::run), expectedExceptionType, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(SecretServiceVersion.values()).filter(SecretClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link SecretServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return SecretServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
Is it preferred to avoid logging at this level for our tests?
void setSecretRunner(Consumer<KeyVaultSecret> testRunner) { final Map<String, String> tags = Collections.singletonMap("foo", "baz"); String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags) .setContentType("text")); testRunner.accept(secretToSet); }
.setTags(tags)
void setSecretRunner(Consumer<KeyVaultSecret> testRunner) { final Map<String, String> tags = Collections.singletonMap("foo", "baz"); String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags) .setContentType("text")); testRunner.accept(secretToSet); }
class SecretClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_SECRETS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS); private static final String SECRET_NAME = "javaSecretTemp"; private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; private static final int MAX_RETRIES = 5; private static final RetryOptions LIVE_RETRY_OPTIONS = new RetryOptions(new ExponentialBackoffOptions() .setMaxRetries(MAX_RETRIES) .setBaseDelay(Duration.ofSeconds(2)) .setMaxDelay(Duration.ofSeconds(16))); private static final RetryOptions PLAYBACK_RETRY_OPTIONS = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); } SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, SecretServiceVersion serviceVersion) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } SecretClientBuilder builder = new SecretClientBuilder() .vaultUrl(endpoint) .serviceVersion(serviceVersion) .credential(credential) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); return interceptorManager.isRecordMode() ? builder.addPolicy(interceptorManager.getRecordPolicy()) : builder; } } @Test public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion); void setSecretEmptyValueRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, ""); testRunner.accept(secretToSet); } @Test public abstract void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); String resourceId = testResourceNamer.randomName("testSecretUpdate", 20); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateDisabledSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testUpdateOfDisabledSecret", 35); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGet", 20); final KeyVaultSecret secretToGet = new KeyVaultSecret(resourceId, "testSecretGetVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToGet); } @Test public abstract void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretSpecificVersionRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetVersion", 30); final KeyVaultSecret secretWithOriginalValue = new KeyVaultSecret(resourceId, "testSecretGetVersionVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); final KeyVaultSecret secretWithNewValue = new KeyVaultSecret(resourceId, "newVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretWithOriginalValue, secretWithNewValue); } @Test public abstract void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void deleteSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretDelete", 20); final KeyVaultSecret secretToDelete = new KeyVaultSecret(resourceId, "testSecretDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDelete); } @Test public abstract void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetDeleted", 25); final KeyVaultSecret secretToDeleteAndGet = new KeyVaultSecret(resourceId, "testSecretGetDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndGet); } @Test public abstract void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void recoverDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretRecover", 25); final KeyVaultSecret secretToDeleteAndRecover = new KeyVaultSecret(resourceId, "testSecretRecoverVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndRecover); } @Test public abstract void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void backupSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackup = new KeyVaultSecret(testResourceNamer.randomName("testSecretBackup", 20), "testSecretBackupVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackup); } @Test public abstract void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void restoreSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackupAndRestore = new KeyVaultSecret(testResourceNamer.randomName("testSecretRestore", 20), "testSecretRestoreVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2080, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackupAndRestore); } @Test public abstract void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretsToSetAndList = new HashMap<>(); for (int i = 0; i < 2; i++) { String secretName = testResourceNamer.randomName("listSecret", 20); String secretVal = "listSecretVal" + i; KeyVaultSecret secret = new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); secretsToSetAndList.put(secretName, secret); } testRunner.accept(secretsToSetAndList); } @Test public abstract void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listDeletedSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretSecretsToSetAndDelete = new HashMap<>(); for (int i = 0; i < 3; i++) { String secretName = testResourceNamer.randomName("listDeletedSecretsTest", 20); String secretVal = "listDeletedSecretVal" + i; secretSecretsToSetAndDelete.put(secretName, new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretSecretsToSetAndDelete); } @Test public abstract void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretVersionsRunner(Consumer<List<KeyVaultSecret>> testRunner) { List<KeyVaultSecret> secretsToSetAndList = new ArrayList<>(); String secretVal; String secretName = testResourceNamer.randomName("listSecretVersion", 20); for (int i = 1; i < 5; i++) { secretVal = "listSecretVersionVal" + i; secretsToSetAndList.add(new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretsToSetAndList); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting contained in the RestResponse body. */ static void assertSecretEquals(KeyVaultSecret expected, KeyVaultSecret actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getProperties().getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getProperties().getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertRestException(assertThrows(expectedExceptionType, exceptionThrower::run), expectedExceptionType, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(SecretServiceVersion.values()).filter(SecretClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link SecretServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return SecretServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
class SecretClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_SECRETS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS); private static final String SECRET_NAME = "javaSecretTemp"; private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; private static final int MAX_RETRIES = 5; private static final RetryOptions LIVE_RETRY_OPTIONS = new RetryOptions(new ExponentialBackoffOptions() .setMaxRetries(MAX_RETRIES) .setBaseDelay(Duration.ofSeconds(2)) .setMaxDelay(Duration.ofSeconds(16))); private static final RetryOptions PLAYBACK_RETRY_OPTIONS = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); } SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, SecretServiceVersion serviceVersion) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } SecretClientBuilder builder = new SecretClientBuilder() .vaultUrl(endpoint) .serviceVersion(serviceVersion) .credential(credential) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); return interceptorManager.isRecordMode() ? builder.addPolicy(interceptorManager.getRecordPolicy()) : builder; } } @Test public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion); void setSecretEmptyValueRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, ""); testRunner.accept(secretToSet); } @Test public abstract void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); String resourceId = testResourceNamer.randomName("testSecretUpdate", 20); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateDisabledSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testUpdateOfDisabledSecret", 35); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGet", 20); final KeyVaultSecret secretToGet = new KeyVaultSecret(resourceId, "testSecretGetVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToGet); } @Test public abstract void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretSpecificVersionRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetVersion", 30); final KeyVaultSecret secretWithOriginalValue = new KeyVaultSecret(resourceId, "testSecretGetVersionVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); final KeyVaultSecret secretWithNewValue = new KeyVaultSecret(resourceId, "newVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretWithOriginalValue, secretWithNewValue); } @Test public abstract void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void deleteSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretDelete", 20); final KeyVaultSecret secretToDelete = new KeyVaultSecret(resourceId, "testSecretDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDelete); } @Test public abstract void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetDeleted", 25); final KeyVaultSecret secretToDeleteAndGet = new KeyVaultSecret(resourceId, "testSecretGetDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndGet); } @Test public abstract void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void recoverDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretRecover", 25); final KeyVaultSecret secretToDeleteAndRecover = new KeyVaultSecret(resourceId, "testSecretRecoverVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndRecover); } @Test public abstract void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void backupSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackup = new KeyVaultSecret(testResourceNamer.randomName("testSecretBackup", 20), "testSecretBackupVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackup); } @Test public abstract void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void restoreSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackupAndRestore = new KeyVaultSecret(testResourceNamer.randomName("testSecretRestore", 20), "testSecretRestoreVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2080, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackupAndRestore); } @Test public abstract void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretsToSetAndList = new HashMap<>(); for (int i = 0; i < 2; i++) { String secretName = testResourceNamer.randomName("listSecret", 20); String secretVal = "listSecretVal" + i; KeyVaultSecret secret = new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); secretsToSetAndList.put(secretName, secret); } testRunner.accept(secretsToSetAndList); } @Test public abstract void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listDeletedSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretSecretsToSetAndDelete = new HashMap<>(); for (int i = 0; i < 3; i++) { String secretName = testResourceNamer.randomName("listDeletedSecretsTest", 20); String secretVal = "listDeletedSecretVal" + i; secretSecretsToSetAndDelete.put(secretName, new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretSecretsToSetAndDelete); } @Test public abstract void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretVersionsRunner(Consumer<List<KeyVaultSecret>> testRunner) { List<KeyVaultSecret> secretsToSetAndList = new ArrayList<>(); String secretVal; String secretName = testResourceNamer.randomName("listSecretVersion", 20); for (int i = 1; i < 5; i++) { secretVal = "listSecretVersionVal" + i; secretsToSetAndList.add(new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretsToSetAndList); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting contained in the RestResponse body. */ static void assertSecretEquals(KeyVaultSecret expected, KeyVaultSecret actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getProperties().getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getProperties().getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertRestException(assertThrows(expectedExceptionType, exceptionThrower::run), expectedExceptionType, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(SecretServiceVersion.values()).filter(SecretClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link SecretServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return SecretServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
Good catch, didn't run into any issues without it. I'll see about adding this back.
void setSecretRunner(Consumer<KeyVaultSecret> testRunner) { final Map<String, String> tags = Collections.singletonMap("foo", "baz"); String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags) .setContentType("text")); testRunner.accept(secretToSet); }
final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE)
void setSecretRunner(Consumer<KeyVaultSecret> testRunner) { final Map<String, String> tags = Collections.singletonMap("foo", "baz"); String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags) .setContentType("text")); testRunner.accept(secretToSet); }
class SecretClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_SECRETS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS); private static final String SECRET_NAME = "javaSecretTemp"; private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; private static final int MAX_RETRIES = 5; private static final RetryOptions LIVE_RETRY_OPTIONS = new RetryOptions(new ExponentialBackoffOptions() .setMaxRetries(MAX_RETRIES) .setBaseDelay(Duration.ofSeconds(2)) .setMaxDelay(Duration.ofSeconds(16))); private static final RetryOptions PLAYBACK_RETRY_OPTIONS = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); } SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, SecretServiceVersion serviceVersion) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } SecretClientBuilder builder = new SecretClientBuilder() .vaultUrl(endpoint) .serviceVersion(serviceVersion) .credential(credential) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); return interceptorManager.isRecordMode() ? builder.addPolicy(interceptorManager.getRecordPolicy()) : builder; } } @Test public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion); void setSecretEmptyValueRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, ""); testRunner.accept(secretToSet); } @Test public abstract void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); String resourceId = testResourceNamer.randomName("testSecretUpdate", 20); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateDisabledSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testUpdateOfDisabledSecret", 35); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGet", 20); final KeyVaultSecret secretToGet = new KeyVaultSecret(resourceId, "testSecretGetVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToGet); } @Test public abstract void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretSpecificVersionRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetVersion", 30); final KeyVaultSecret secretWithOriginalValue = new KeyVaultSecret(resourceId, "testSecretGetVersionVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); final KeyVaultSecret secretWithNewValue = new KeyVaultSecret(resourceId, "newVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretWithOriginalValue, secretWithNewValue); } @Test public abstract void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void deleteSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretDelete", 20); final KeyVaultSecret secretToDelete = new KeyVaultSecret(resourceId, "testSecretDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDelete); } @Test public abstract void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetDeleted", 25); final KeyVaultSecret secretToDeleteAndGet = new KeyVaultSecret(resourceId, "testSecretGetDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndGet); } @Test public abstract void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void recoverDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretRecover", 25); final KeyVaultSecret secretToDeleteAndRecover = new KeyVaultSecret(resourceId, "testSecretRecoverVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndRecover); } @Test public abstract void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void backupSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackup = new KeyVaultSecret(testResourceNamer.randomName("testSecretBackup", 20), "testSecretBackupVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackup); } @Test public abstract void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void restoreSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackupAndRestore = new KeyVaultSecret(testResourceNamer.randomName("testSecretRestore", 20), "testSecretRestoreVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2080, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackupAndRestore); } @Test public abstract void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretsToSetAndList = new HashMap<>(); for (int i = 0; i < 2; i++) { String secretName = testResourceNamer.randomName("listSecret", 20); String secretVal = "listSecretVal" + i; KeyVaultSecret secret = new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); secretsToSetAndList.put(secretName, secret); } testRunner.accept(secretsToSetAndList); } @Test public abstract void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listDeletedSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretSecretsToSetAndDelete = new HashMap<>(); for (int i = 0; i < 3; i++) { String secretName = testResourceNamer.randomName("listDeletedSecretsTest", 20); String secretVal = "listDeletedSecretVal" + i; secretSecretsToSetAndDelete.put(secretName, new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretSecretsToSetAndDelete); } @Test public abstract void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretVersionsRunner(Consumer<List<KeyVaultSecret>> testRunner) { List<KeyVaultSecret> secretsToSetAndList = new ArrayList<>(); String secretVal; String secretName = testResourceNamer.randomName("listSecretVersion", 20); for (int i = 1; i < 5; i++) { secretVal = "listSecretVersionVal" + i; secretsToSetAndList.add(new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretsToSetAndList); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting contained in the RestResponse body. */ static void assertSecretEquals(KeyVaultSecret expected, KeyVaultSecret actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getProperties().getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getProperties().getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertRestException(assertThrows(expectedExceptionType, exceptionThrower::run), expectedExceptionType, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(SecretServiceVersion.values()).filter(SecretClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link SecretServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return SecretServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
class SecretClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_SECRETS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS); private static final String SECRET_NAME = "javaSecretTemp"; private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; private static final int MAX_RETRIES = 5; private static final RetryOptions LIVE_RETRY_OPTIONS = new RetryOptions(new ExponentialBackoffOptions() .setMaxRetries(MAX_RETRIES) .setBaseDelay(Duration.ofSeconds(2)) .setMaxDelay(Duration.ofSeconds(16))); private static final RetryOptions PLAYBACK_RETRY_OPTIONS = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); } SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, SecretServiceVersion serviceVersion) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } SecretClientBuilder builder = new SecretClientBuilder() .vaultUrl(endpoint) .serviceVersion(serviceVersion) .credential(credential) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); return interceptorManager.isRecordMode() ? builder.addPolicy(interceptorManager.getRecordPolicy()) : builder; } } @Test public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion); void setSecretEmptyValueRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, ""); testRunner.accept(secretToSet); } @Test public abstract void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); String resourceId = testResourceNamer.randomName("testSecretUpdate", 20); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateDisabledSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testUpdateOfDisabledSecret", 35); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGet", 20); final KeyVaultSecret secretToGet = new KeyVaultSecret(resourceId, "testSecretGetVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToGet); } @Test public abstract void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretSpecificVersionRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetVersion", 30); final KeyVaultSecret secretWithOriginalValue = new KeyVaultSecret(resourceId, "testSecretGetVersionVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); final KeyVaultSecret secretWithNewValue = new KeyVaultSecret(resourceId, "newVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretWithOriginalValue, secretWithNewValue); } @Test public abstract void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void deleteSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretDelete", 20); final KeyVaultSecret secretToDelete = new KeyVaultSecret(resourceId, "testSecretDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDelete); } @Test public abstract void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetDeleted", 25); final KeyVaultSecret secretToDeleteAndGet = new KeyVaultSecret(resourceId, "testSecretGetDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndGet); } @Test public abstract void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void recoverDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretRecover", 25); final KeyVaultSecret secretToDeleteAndRecover = new KeyVaultSecret(resourceId, "testSecretRecoverVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndRecover); } @Test public abstract void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void backupSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackup = new KeyVaultSecret(testResourceNamer.randomName("testSecretBackup", 20), "testSecretBackupVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackup); } @Test public abstract void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void restoreSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackupAndRestore = new KeyVaultSecret(testResourceNamer.randomName("testSecretRestore", 20), "testSecretRestoreVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2080, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackupAndRestore); } @Test public abstract void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretsToSetAndList = new HashMap<>(); for (int i = 0; i < 2; i++) { String secretName = testResourceNamer.randomName("listSecret", 20); String secretVal = "listSecretVal" + i; KeyVaultSecret secret = new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); secretsToSetAndList.put(secretName, secret); } testRunner.accept(secretsToSetAndList); } @Test public abstract void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listDeletedSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretSecretsToSetAndDelete = new HashMap<>(); for (int i = 0; i < 3; i++) { String secretName = testResourceNamer.randomName("listDeletedSecretsTest", 20); String secretVal = "listDeletedSecretVal" + i; secretSecretsToSetAndDelete.put(secretName, new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretSecretsToSetAndDelete); } @Test public abstract void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretVersionsRunner(Consumer<List<KeyVaultSecret>> testRunner) { List<KeyVaultSecret> secretsToSetAndList = new ArrayList<>(); String secretVal; String secretName = testResourceNamer.randomName("listSecretVersion", 20); for (int i = 1; i < 5; i++) { secretVal = "listSecretVersionVal" + i; secretsToSetAndList.add(new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretsToSetAndList); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting contained in the RestResponse body. */ static void assertSecretEquals(KeyVaultSecret expected, KeyVaultSecret actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getProperties().getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getProperties().getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertRestException(assertThrows(expectedExceptionType, exceptionThrower::run), expectedExceptionType, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(SecretServiceVersion.values()).filter(SecretClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link SecretServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return SecretServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
It really doesn't do much as this still requires a logger to be enabled and this can now be set using environment variables.
void setSecretRunner(Consumer<KeyVaultSecret> testRunner) { final Map<String, String> tags = Collections.singletonMap("foo", "baz"); String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags) .setContentType("text")); testRunner.accept(secretToSet); }
.setTags(tags)
void setSecretRunner(Consumer<KeyVaultSecret> testRunner) { final Map<String, String> tags = Collections.singletonMap("foo", "baz"); String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags) .setContentType("text")); testRunner.accept(secretToSet); }
class SecretClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_SECRETS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS); private static final String SECRET_NAME = "javaSecretTemp"; private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; private static final int MAX_RETRIES = 5; private static final RetryOptions LIVE_RETRY_OPTIONS = new RetryOptions(new ExponentialBackoffOptions() .setMaxRetries(MAX_RETRIES) .setBaseDelay(Duration.ofSeconds(2)) .setMaxDelay(Duration.ofSeconds(16))); private static final RetryOptions PLAYBACK_RETRY_OPTIONS = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); } SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, SecretServiceVersion serviceVersion) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } SecretClientBuilder builder = new SecretClientBuilder() .vaultUrl(endpoint) .serviceVersion(serviceVersion) .credential(credential) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); return interceptorManager.isRecordMode() ? builder.addPolicy(interceptorManager.getRecordPolicy()) : builder; } } @Test public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion); void setSecretEmptyValueRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, ""); testRunner.accept(secretToSet); } @Test public abstract void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); String resourceId = testResourceNamer.randomName("testSecretUpdate", 20); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateDisabledSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testUpdateOfDisabledSecret", 35); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGet", 20); final KeyVaultSecret secretToGet = new KeyVaultSecret(resourceId, "testSecretGetVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToGet); } @Test public abstract void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretSpecificVersionRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetVersion", 30); final KeyVaultSecret secretWithOriginalValue = new KeyVaultSecret(resourceId, "testSecretGetVersionVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); final KeyVaultSecret secretWithNewValue = new KeyVaultSecret(resourceId, "newVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretWithOriginalValue, secretWithNewValue); } @Test public abstract void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void deleteSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretDelete", 20); final KeyVaultSecret secretToDelete = new KeyVaultSecret(resourceId, "testSecretDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDelete); } @Test public abstract void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetDeleted", 25); final KeyVaultSecret secretToDeleteAndGet = new KeyVaultSecret(resourceId, "testSecretGetDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndGet); } @Test public abstract void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void recoverDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretRecover", 25); final KeyVaultSecret secretToDeleteAndRecover = new KeyVaultSecret(resourceId, "testSecretRecoverVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndRecover); } @Test public abstract void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void backupSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackup = new KeyVaultSecret(testResourceNamer.randomName("testSecretBackup", 20), "testSecretBackupVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackup); } @Test public abstract void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void restoreSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackupAndRestore = new KeyVaultSecret(testResourceNamer.randomName("testSecretRestore", 20), "testSecretRestoreVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2080, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackupAndRestore); } @Test public abstract void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretsToSetAndList = new HashMap<>(); for (int i = 0; i < 2; i++) { String secretName = testResourceNamer.randomName("listSecret", 20); String secretVal = "listSecretVal" + i; KeyVaultSecret secret = new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); secretsToSetAndList.put(secretName, secret); } testRunner.accept(secretsToSetAndList); } @Test public abstract void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listDeletedSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretSecretsToSetAndDelete = new HashMap<>(); for (int i = 0; i < 3; i++) { String secretName = testResourceNamer.randomName("listDeletedSecretsTest", 20); String secretVal = "listDeletedSecretVal" + i; secretSecretsToSetAndDelete.put(secretName, new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretSecretsToSetAndDelete); } @Test public abstract void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretVersionsRunner(Consumer<List<KeyVaultSecret>> testRunner) { List<KeyVaultSecret> secretsToSetAndList = new ArrayList<>(); String secretVal; String secretName = testResourceNamer.randomName("listSecretVersion", 20); for (int i = 1; i < 5; i++) { secretVal = "listSecretVersionVal" + i; secretsToSetAndList.add(new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretsToSetAndList); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting contained in the RestResponse body. */ static void assertSecretEquals(KeyVaultSecret expected, KeyVaultSecret actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getProperties().getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getProperties().getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertRestException(assertThrows(expectedExceptionType, exceptionThrower::run), expectedExceptionType, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(SecretServiceVersion.values()).filter(SecretClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link SecretServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return SecretServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
class SecretClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_SECRETS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS); private static final String SECRET_NAME = "javaSecretTemp"; private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; private static final int MAX_RETRIES = 5; private static final RetryOptions LIVE_RETRY_OPTIONS = new RetryOptions(new ExponentialBackoffOptions() .setMaxRetries(MAX_RETRIES) .setBaseDelay(Duration.ofSeconds(2)) .setMaxDelay(Duration.ofSeconds(16))); private static final RetryOptions PLAYBACK_RETRY_OPTIONS = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); } SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, SecretServiceVersion serviceVersion) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } SecretClientBuilder builder = new SecretClientBuilder() .vaultUrl(endpoint) .serviceVersion(serviceVersion) .credential(credential) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); return interceptorManager.isRecordMode() ? builder.addPolicy(interceptorManager.getRecordPolicy()) : builder; } } @Test public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion); void setSecretEmptyValueRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, ""); testRunner.accept(secretToSet); } @Test public abstract void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); String resourceId = testResourceNamer.randomName("testSecretUpdate", 20); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void updateDisabledSecretRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testUpdateOfDisabledSecret", 35); final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false)); testRunner.accept(originalSecret, updatedSecret); } @Test public abstract void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGet", 20); final KeyVaultSecret secretToGet = new KeyVaultSecret(resourceId, "testSecretGetVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToGet); } @Test public abstract void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion); void getSecretSpecificVersionRunner(BiConsumer<KeyVaultSecret, KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetVersion", 30); final KeyVaultSecret secretWithOriginalValue = new KeyVaultSecret(resourceId, "testSecretGetVersionVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); final KeyVaultSecret secretWithNewValue = new KeyVaultSecret(resourceId, "newVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretWithOriginalValue, secretWithNewValue); } @Test public abstract void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void deleteSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretDelete", 20); final KeyVaultSecret secretToDelete = new KeyVaultSecret(resourceId, "testSecretDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDelete); } @Test public abstract void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void getDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretGetDeleted", 25); final KeyVaultSecret secretToDeleteAndGet = new KeyVaultSecret(resourceId, "testSecretGetDeleteVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndGet); } @Test public abstract void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void recoverDeletedSecretRunner(Consumer<KeyVaultSecret> testRunner) { String resourceId = testResourceNamer.randomName("testSecretRecover", 25); final KeyVaultSecret secretToDeleteAndRecover = new KeyVaultSecret(resourceId, "testSecretRecoverVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToDeleteAndRecover); } @Test public abstract void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void backupSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackup = new KeyVaultSecret(testResourceNamer.randomName("testSecretBackup", 20), "testSecretBackupVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackup); } @Test public abstract void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); void restoreSecretRunner(Consumer<KeyVaultSecret> testRunner) { final KeyVaultSecret secretToBackupAndRestore = new KeyVaultSecret(testResourceNamer.randomName("testSecretRestore", 20), "testSecretRestoreVal") .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2080, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); testRunner.accept(secretToBackupAndRestore); } @Test public abstract void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion); @Test public abstract void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretsToSetAndList = new HashMap<>(); for (int i = 0; i < 2; i++) { String secretName = testResourceNamer.randomName("listSecret", 20); String secretVal = "listSecretVal" + i; KeyVaultSecret secret = new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); secretsToSetAndList.put(secretName, secret); } testRunner.accept(secretsToSetAndList); } @Test public abstract void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); void listDeletedSecretsRunner(Consumer<HashMap<String, KeyVaultSecret>> testRunner) { HashMap<String, KeyVaultSecret> secretSecretsToSetAndDelete = new HashMap<>(); for (int i = 0; i < 3; i++) { String secretName = testResourceNamer.randomName("listDeletedSecretsTest", 20); String secretVal = "listDeletedSecretVal" + i; secretSecretsToSetAndDelete.put(secretName, new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretSecretsToSetAndDelete); } @Test public abstract void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion); void listSecretVersionsRunner(Consumer<List<KeyVaultSecret>> testRunner) { List<KeyVaultSecret> secretsToSetAndList = new ArrayList<>(); String secretVal; String secretName = testResourceNamer.randomName("listSecretVersion", 20); for (int i = 1; i < 5; i++) { secretVal = "listSecretVersionVal" + i; secretsToSetAndList.add(new KeyVaultSecret(secretName, secretVal) .setProperties(new SecretProperties() .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC)))); } testRunner.accept(secretsToSetAndList); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting contained in the RestResponse body. */ static void assertSecretEquals(KeyVaultSecret expected, KeyVaultSecret actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getProperties().getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getProperties().getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertRestException(assertThrows(expectedExceptionType, exceptionThrower::run), expectedExceptionType, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(SecretServiceVersion.values()).filter(SecretClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link SecretServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return SecretServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
@JonathanGiles, @srnagar, @lmolkova this is a new exception being thrown checking that the `name` is non-null. While this is a breaking change as this adds a new exception being thrown this fixes a larger issue where the REST API paths used by KeyVault here is `GET {keyVaultUrl}/secrets/{secretName}/{secretVersion}` for getting a single secret and `GET {keyVaultUrl}/secrets` for listing secrets. This leaves a possibility when name and version is null or empty string for the final URL to become `GET {keyVaultUrl}/secrets//` which ends up calling into the listing resulting in a deserialization exception as the response type is different in that API. FYI @vcolin7
public Response<KeyVaultSecret> getSecretWithResponse(String name, String version, Context context) { Objects.requireNonNull(name, "Secret name cannot be null."); return callWithMappedException(() -> { Response<SecretBundle> response = implClient.getSecretWithResponse(vaultUrl, name, version, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapGetSecretException); }
Objects.requireNonNull(name, "Secret name cannot be null.");
public Response<KeyVaultSecret> getSecretWithResponse(String name, String version, Context context) { if (CoreUtils.isNullOrEmpty(name)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'name' cannot be null or empty.")); } return callWithMappedException(() -> { Response<SecretBundle> response = implClient.getSecretWithResponse(vaultUrl, name, version, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapGetSecretException); }
class SecretClient { private final SecretClientImpl implClient; private final String vaultUrl; /** * Gets the vault endpoint url to which service requests are sent to. * @return the vault endpoint url. */ public String getVaultUrl() { return vaultUrl; } /** * Creates a SecretClient to service requests * * @param implClient the implementation client. * @param vaultUrl the vault url. */ SecretClient(SecretClientImpl implClient, String vaultUrl) { this.implClient = implClient; this.vaultUrl = vaultUrl; } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p>The {@link SecretProperties * and {@link SecretProperties * If not specified, {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret returnedSecret = secretClient.setSecret& * System.out.printf& * returnedSecret.getValue& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret * @return The {@link KeyVaultSecret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpResponseException if {@link KeyVaultSecret * is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(KeyVaultSecret secret) { return setSecretWithResponse(secret, Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret secret = secretClient.setSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. * @return The {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(String name, String value) { return setSecretWithResponse(new KeyVaultSecret(name, value), Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecretWithResponse * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret secret = secretClient.setSecretWithResponse& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecretWithResponse * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> setSecretWithResponse(KeyVaultSecret secret, Context context) { return callWithMappedException(() -> { SecretProperties secretProperties = secret.getProperties(); if (secretProperties == null) { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), null, ContentType.APPLICATION_JSON, null, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } else { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), secretProperties.getTags(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } }, SecretAsyncClient::mapSetSecretException); } /** * Gets the latest version of the specified secret from the key vault. * This operation requires the {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * KeyVaultSecret secretWithoutVersion = secretClient.getSecret& * System.out.printf& * secretWithoutVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret. * @return The requested {@link KeyVaultSecret}. * @throws NullPointerException if {@code name} is {@code null}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name) { return getSecretWithResponse(name, null, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecret& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this call is * equivalent to calling {@link * @return The requested {@link KeyVaultSecret secret}. * @throws NullPointerException if {@code name} is {@code null}. * @throws ResourceNotFoundException when a secret with {@code name} and {@code version} doesn't exist in the key * vault. * @throws HttpResponseException if {@code name} and {@code version} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name, String version) { return getSecretWithResponse(name, version, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecretWithResponse * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse& * new Context& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecretWithResponse * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent * to calling {@link * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws NullPointerException if {@code name} is {@code null}. * @throws ResourceNotFoundException when a secret with {@code name} and {@code version} doesn't exist in the key * vault. * @throws HttpResponseException if {@code name} and {@code version} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key * vault.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretProperties * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretProperties = secretClient.updateSecretProperties& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretProperties * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @return The {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public SecretProperties updateSecretProperties(SecretProperties secretProperties) { return updateSecretPropertiesWithResponse(secretProperties, Context.NONE).getValue(); } /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key vault. * </p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse& * new Context& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<SecretProperties> updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { Response<SecretBundle> response = implClient.updateSecretWithResponse(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), secretProperties.getTags(), context); return new SimpleResponse<>(response, createSecretProperties(response.getValue())); } /** * Deletes a secret from the key vault. If soft-delete is enabled on the key vault then the secret is placed in the * deleted state and for permanent deletion, needs to be purged. Otherwise, the secret is permanently deleted. * All versions of a secret are deleted. This cannot be applied to individual versions of a secret. * This operation requires the {@code secrets/delete} permission. * * <p><strong>Code sample</strong></p> * <p>Deletes the secret from a soft-delete enabled key vault. Prints out the recovery id of the deleted secret * returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.deleteSecret * <pre> * SyncPoller&lt;DeletedSecret, Void&gt; deleteSecretPoller = secretClient.beginDeleteSecret& * * & * PollResponse&lt;DeletedSecret&gt; deleteSecretPollResponse = deleteSecretPoller.poll& * * & * System.out.println& * .getDeletedOn& * System.out.printf& * .getRecoveryId& * * & * deleteSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.deleteSecret * * @param name The name of the secret to be deleted. * @return A {@link SyncPoller} to poll on and retrieve the {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<DeletedSecret, Void> beginDeleteSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), deleteActivationOperation(name), deletePollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deleteActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createDeletedSecret(implClient.deleteSecret(vaultUrl, name))), SecretAsyncClient::mapDeleteSecretException); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deletePollOperation(String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createDeletedSecret(implClient.getDeletedSecret(vaultUrl, name))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecret * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecret * * @param name The name of the deleted secret. * @return The {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public DeletedSecret getDeletedSecret(String name) { return getDeletedSecretWithResponse(name, Context.NONE).getValue(); } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * * @param name The name of the deleted secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<DeletedSecret> getDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<DeletedSecretBundle> response = implClient.getDeletedSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, createDeletedSecret(response.getValue())); }, SecretAsyncClient::mapGetDeletedSecretException); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecret * <pre> * secretClient.purgeDeletedSecret& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecret * * @param name The name of the secret. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public void purgeDeletedSecret(String name) { purgeDeletedSecretWithResponse(name, Context.NONE); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * <pre> * Response&lt;Void&gt; purgeResponse = secretClient.purgeDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> purgeDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> implClient.purgeDeletedSecretWithResponse(vaultUrl, name, context), SecretAsyncClient::mapPurgeDeletedSecretException); } /** * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a <b>soft-delete * enabled</b> vault. This operation requires the {@code secrets/recover} permission. * * <p><strong>Code sample</strong></p> * <p>Recovers the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the details of the * recovered secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.recoverDeletedSecret * <pre> * SyncPoller&lt;KeyVaultSecret, Void&gt; recoverSecretPoller = * secretClient.beginRecoverDeletedSecret& * * & * PollResponse&lt;KeyVaultSecret&gt; recoveredSecretPollResponse = recoverSecretPoller.poll& * System.out.println& * System.out.printf& * * & * recoverSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.recoverDeletedSecret * * @param name The name of the deleted secret to be recovered. * @return A {@link SyncPoller} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<KeyVaultSecret, Void> beginRecoverDeletedSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), recoverActivationOperation(name), recoverPollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createKeyVaultSecret(implClient.recoverDeletedSecret(vaultUrl, name))), SecretAsyncClient::mapRecoverDeletedSecretException); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverPollOperation( String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createKeyVaultSecret(implClient.getSecret(vaultUrl, name, null))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecret * <pre> * byte[] secretBackup = secretClient.backupSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecret * * @param name The name of the secret. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public byte[] backupSecret(String name) { return backupSecretWithResponse(name, Context.NONE).getValue(); } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecretWithResponse * <pre> * byte[] secretBackup = secretClient.backupSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<byte[]> backupSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<BackupSecretResult> response = implClient.backupSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, response.getValue().getValue()); }, SecretAsyncClient::mapBackupSecretException); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecret * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecret * * @param backup The backup blob associated with the secret. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret restoreSecretBackup(byte[] backup) { return restoreSecretBackupWithResponse(backup, Context.NONE).getValue(); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse& * new Context& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * * @param backup The backup blob associated with the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> restoreSecretBackupWithResponse(byte[] backup, Context context) { return callWithMappedException(() -> { Response<SecretBundle> response = implClient.restoreSecretWithResponse(vaultUrl, backup, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapRestoreSecretException); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate through secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets --> * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} by page and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * <pre> * secretClient.listPropertiesOfSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. The * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets() { return listPropertiesOfSecrets(Context.NONE); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets(Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretsSinglePage(vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretsNextSinglePage(continuationToken, vaultUrl, context))); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>Iterate over Lists the deleted secrets by page in the key vault and for each deleted secret prints out its * recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * <pre> * secretClient.listDeletedSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * System.out.printf& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets() { return listDeletedSecrets(Context.NONE); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets(Context context) { return new PagedIterable<>(maxResults -> mapDeletedSecretItemPage(implClient.getDeletedSecretsSinglePage( vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapDeletedSecretItemPage(implClient.getDeletedSecretsNextSinglePage( continuationToken, vaultUrl, context))); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name) { return listPropertiesOfSecretVersions(name, Context.NONE); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * .listPropertiesOfSecretVersions& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * <p><strong>Iterate over secret versions by page</strong></p> * <p>The sample below iterates over each {@link SecretProperties secret} by each page and calls * {@link SecretClient * corresponding version's value.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * secretClient.listPropertiesOfSecretVersions& * .iterableByPage& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name, Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretVersionsSinglePage(vaultUrl, name, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretVersionsNextSinglePage( continuationToken, vaultUrl, context))); } private static <T> T callWithMappedException(Supplier<T> call, Function<KeyVaultErrorException, HttpResponseException> exceptionMapper) { try { return call.get(); } catch (KeyVaultErrorException ex) { throw exceptionMapper.apply(ex); } } }
class SecretClient { private static final ClientLogger LOGGER = new ClientLogger(SecretClient.class); private final SecretClientImpl implClient; private final String vaultUrl; /** * Gets the vault endpoint url to which service requests are sent to. * @return the vault endpoint url. */ public String getVaultUrl() { return vaultUrl; } /** * Creates a SecretClient to service requests * * @param implClient the implementation client. * @param vaultUrl the vault url. */ SecretClient(SecretClientImpl implClient, String vaultUrl) { this.implClient = implClient; this.vaultUrl = vaultUrl; } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p>The {@link SecretProperties * and {@link SecretProperties * If not specified, {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret returnedSecret = secretClient.setSecret& * System.out.printf& * returnedSecret.getValue& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret * @return The {@link KeyVaultSecret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpResponseException if {@link KeyVaultSecret * is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(KeyVaultSecret secret) { return setSecretWithResponse(secret, Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret secret = secretClient.setSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. * @return The {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(String name, String value) { return setSecretWithResponse(new KeyVaultSecret(name, value), Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecretWithResponse * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret secret = secretClient.setSecretWithResponse& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecretWithResponse * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> setSecretWithResponse(KeyVaultSecret secret, Context context) { return callWithMappedException(() -> { SecretProperties secretProperties = secret.getProperties(); if (secretProperties == null) { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), null, ContentType.APPLICATION_JSON, null, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } else { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), secretProperties.getTags(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } }, SecretAsyncClient::mapSetSecretException); } /** * Gets the latest version of the specified secret from the key vault. * This operation requires the {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * KeyVaultSecret secretWithoutVersion = secretClient.getSecret& * System.out.printf& * secretWithoutVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret. * @return The requested {@link KeyVaultSecret}. * @throws ResourceNotFoundException When a secret with the given {@code name} doesn't exist in the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. * @throws HttpResponseException If the server reports an error when executing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name) { return getSecretWithResponse(name, null, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecret& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this call is * equivalent to calling {@link * @return The requested {@link KeyVaultSecret secret}. * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in * the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. * @throws HttpResponseException If the server reports an error when executing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name, String version) { return getSecretWithResponse(name, version, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecretWithResponse * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse& * new Context& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecretWithResponse * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent * to calling {@link * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in * the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key * vault.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretProperties * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretProperties = secretClient.updateSecretProperties& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretProperties * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @return The {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public SecretProperties updateSecretProperties(SecretProperties secretProperties) { return updateSecretPropertiesWithResponse(secretProperties, Context.NONE).getValue(); } /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key vault. * </p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse& * new Context& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<SecretProperties> updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { Response<SecretBundle> response = implClient.updateSecretWithResponse(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), secretProperties.getTags(), context); return new SimpleResponse<>(response, createSecretProperties(response.getValue())); } /** * Deletes a secret from the key vault. If soft-delete is enabled on the key vault then the secret is placed in the * deleted state and for permanent deletion, needs to be purged. Otherwise, the secret is permanently deleted. * All versions of a secret are deleted. This cannot be applied to individual versions of a secret. * This operation requires the {@code secrets/delete} permission. * * <p><strong>Code sample</strong></p> * <p>Deletes the secret from a soft-delete enabled key vault. Prints out the recovery id of the deleted secret * returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.deleteSecret * <pre> * SyncPoller&lt;DeletedSecret, Void&gt; deleteSecretPoller = secretClient.beginDeleteSecret& * * & * PollResponse&lt;DeletedSecret&gt; deleteSecretPollResponse = deleteSecretPoller.poll& * * & * System.out.println& * .getDeletedOn& * System.out.printf& * .getRecoveryId& * * & * deleteSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.deleteSecret * * @param name The name of the secret to be deleted. * @return A {@link SyncPoller} to poll on and retrieve the {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<DeletedSecret, Void> beginDeleteSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), deleteActivationOperation(name), deletePollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deleteActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createDeletedSecret(implClient.deleteSecret(vaultUrl, name))), SecretAsyncClient::mapDeleteSecretException); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deletePollOperation(String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createDeletedSecret(implClient.getDeletedSecret(vaultUrl, name))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecret * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecret * * @param name The name of the deleted secret. * @return The {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public DeletedSecret getDeletedSecret(String name) { return getDeletedSecretWithResponse(name, Context.NONE).getValue(); } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * * @param name The name of the deleted secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<DeletedSecret> getDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<DeletedSecretBundle> response = implClient.getDeletedSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, createDeletedSecret(response.getValue())); }, SecretAsyncClient::mapGetDeletedSecretException); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecret * <pre> * secretClient.purgeDeletedSecret& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecret * * @param name The name of the secret. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public void purgeDeletedSecret(String name) { purgeDeletedSecretWithResponse(name, Context.NONE); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * <pre> * Response&lt;Void&gt; purgeResponse = secretClient.purgeDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> purgeDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> implClient.purgeDeletedSecretWithResponse(vaultUrl, name, context), SecretAsyncClient::mapPurgeDeletedSecretException); } /** * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a <b>soft-delete * enabled</b> vault. This operation requires the {@code secrets/recover} permission. * * <p><strong>Code sample</strong></p> * <p>Recovers the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the details of the * recovered secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.recoverDeletedSecret * <pre> * SyncPoller&lt;KeyVaultSecret, Void&gt; recoverSecretPoller = * secretClient.beginRecoverDeletedSecret& * * & * PollResponse&lt;KeyVaultSecret&gt; recoveredSecretPollResponse = recoverSecretPoller.poll& * System.out.println& * System.out.printf& * * & * recoverSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.recoverDeletedSecret * * @param name The name of the deleted secret to be recovered. * @return A {@link SyncPoller} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<KeyVaultSecret, Void> beginRecoverDeletedSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), recoverActivationOperation(name), recoverPollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createKeyVaultSecret(implClient.recoverDeletedSecret(vaultUrl, name))), SecretAsyncClient::mapRecoverDeletedSecretException); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverPollOperation( String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createKeyVaultSecret(implClient.getSecret(vaultUrl, name, null))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecret * <pre> * byte[] secretBackup = secretClient.backupSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecret * * @param name The name of the secret. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public byte[] backupSecret(String name) { return backupSecretWithResponse(name, Context.NONE).getValue(); } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecretWithResponse * <pre> * byte[] secretBackup = secretClient.backupSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<byte[]> backupSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<BackupSecretResult> response = implClient.backupSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, response.getValue().getValue()); }, SecretAsyncClient::mapBackupSecretException); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecret * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecret * * @param backup The backup blob associated with the secret. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret restoreSecretBackup(byte[] backup) { return restoreSecretBackupWithResponse(backup, Context.NONE).getValue(); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse& * new Context& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * * @param backup The backup blob associated with the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> restoreSecretBackupWithResponse(byte[] backup, Context context) { return callWithMappedException(() -> { Response<SecretBundle> response = implClient.restoreSecretWithResponse(vaultUrl, backup, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapRestoreSecretException); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate through secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets --> * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} by page and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * <pre> * secretClient.listPropertiesOfSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. The * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets() { return listPropertiesOfSecrets(Context.NONE); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets(Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretsSinglePage(vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretsNextSinglePage(continuationToken, vaultUrl, context))); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>Iterate over Lists the deleted secrets by page in the key vault and for each deleted secret prints out its * recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * <pre> * secretClient.listDeletedSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * System.out.printf& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets() { return listDeletedSecrets(Context.NONE); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets(Context context) { return new PagedIterable<>(maxResults -> mapDeletedSecretItemPage(implClient.getDeletedSecretsSinglePage( vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapDeletedSecretItemPage(implClient.getDeletedSecretsNextSinglePage( continuationToken, vaultUrl, context))); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name) { return listPropertiesOfSecretVersions(name, Context.NONE); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * .listPropertiesOfSecretVersions& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * <p><strong>Iterate over secret versions by page</strong></p> * <p>The sample below iterates over each {@link SecretProperties secret} by each page and calls * {@link SecretClient * corresponding version's value.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * secretClient.listPropertiesOfSecretVersions& * .iterableByPage& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name, Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretVersionsSinglePage(vaultUrl, name, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretVersionsNextSinglePage( continuationToken, vaultUrl, context))); } private static <T> T callWithMappedException(Supplier<T> call, Function<KeyVaultErrorException, HttpResponseException> exceptionMapper) { try { return call.get(); } catch (KeyVaultErrorException ex) { throw exceptionMapper.apply(ex); } } }
I think we should consider changing this to check to ensure the name is neither `null` nor empty. Passing an empty string value will also try to [list all secrets](https://github.com/Azure/azure-sdk-for-java/issues/32460#issuecomment-1426559885). Even if it means having a new exception being thrown, the fact that the request would ultimately fail with an `HttpResponseException` with the message `Deserialization Failed` gives us wiggle room to use a more appropriate one, such as `NullPointerException` or `IllegalArgumentException`.
public Response<KeyVaultSecret> getSecretWithResponse(String name, String version, Context context) { Objects.requireNonNull(name, "Secret name cannot be null."); return callWithMappedException(() -> { Response<SecretBundle> response = implClient.getSecretWithResponse(vaultUrl, name, version, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapGetSecretException); }
Objects.requireNonNull(name, "Secret name cannot be null.");
public Response<KeyVaultSecret> getSecretWithResponse(String name, String version, Context context) { if (CoreUtils.isNullOrEmpty(name)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'name' cannot be null or empty.")); } return callWithMappedException(() -> { Response<SecretBundle> response = implClient.getSecretWithResponse(vaultUrl, name, version, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapGetSecretException); }
class SecretClient { private final SecretClientImpl implClient; private final String vaultUrl; /** * Gets the vault endpoint url to which service requests are sent to. * @return the vault endpoint url. */ public String getVaultUrl() { return vaultUrl; } /** * Creates a SecretClient to service requests * * @param implClient the implementation client. * @param vaultUrl the vault url. */ SecretClient(SecretClientImpl implClient, String vaultUrl) { this.implClient = implClient; this.vaultUrl = vaultUrl; } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p>The {@link SecretProperties * and {@link SecretProperties * If not specified, {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret returnedSecret = secretClient.setSecret& * System.out.printf& * returnedSecret.getValue& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret * @return The {@link KeyVaultSecret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpResponseException if {@link KeyVaultSecret * is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(KeyVaultSecret secret) { return setSecretWithResponse(secret, Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret secret = secretClient.setSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. * @return The {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(String name, String value) { return setSecretWithResponse(new KeyVaultSecret(name, value), Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecretWithResponse * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret secret = secretClient.setSecretWithResponse& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecretWithResponse * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> setSecretWithResponse(KeyVaultSecret secret, Context context) { return callWithMappedException(() -> { SecretProperties secretProperties = secret.getProperties(); if (secretProperties == null) { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), null, ContentType.APPLICATION_JSON, null, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } else { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), secretProperties.getTags(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } }, SecretAsyncClient::mapSetSecretException); } /** * Gets the latest version of the specified secret from the key vault. * This operation requires the {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * KeyVaultSecret secretWithoutVersion = secretClient.getSecret& * System.out.printf& * secretWithoutVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret. * @return The requested {@link KeyVaultSecret}. * @throws NullPointerException if {@code name} is {@code null}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name) { return getSecretWithResponse(name, null, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecret& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this call is * equivalent to calling {@link * @return The requested {@link KeyVaultSecret secret}. * @throws NullPointerException if {@code name} is {@code null}. * @throws ResourceNotFoundException when a secret with {@code name} and {@code version} doesn't exist in the key * vault. * @throws HttpResponseException if {@code name} and {@code version} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name, String version) { return getSecretWithResponse(name, version, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecretWithResponse * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse& * new Context& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecretWithResponse * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent * to calling {@link * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws NullPointerException if {@code name} is {@code null}. * @throws ResourceNotFoundException when a secret with {@code name} and {@code version} doesn't exist in the key * vault. * @throws HttpResponseException if {@code name} and {@code version} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key * vault.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretProperties * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretProperties = secretClient.updateSecretProperties& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretProperties * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @return The {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public SecretProperties updateSecretProperties(SecretProperties secretProperties) { return updateSecretPropertiesWithResponse(secretProperties, Context.NONE).getValue(); } /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key vault. * </p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse& * new Context& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<SecretProperties> updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { Response<SecretBundle> response = implClient.updateSecretWithResponse(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), secretProperties.getTags(), context); return new SimpleResponse<>(response, createSecretProperties(response.getValue())); } /** * Deletes a secret from the key vault. If soft-delete is enabled on the key vault then the secret is placed in the * deleted state and for permanent deletion, needs to be purged. Otherwise, the secret is permanently deleted. * All versions of a secret are deleted. This cannot be applied to individual versions of a secret. * This operation requires the {@code secrets/delete} permission. * * <p><strong>Code sample</strong></p> * <p>Deletes the secret from a soft-delete enabled key vault. Prints out the recovery id of the deleted secret * returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.deleteSecret * <pre> * SyncPoller&lt;DeletedSecret, Void&gt; deleteSecretPoller = secretClient.beginDeleteSecret& * * & * PollResponse&lt;DeletedSecret&gt; deleteSecretPollResponse = deleteSecretPoller.poll& * * & * System.out.println& * .getDeletedOn& * System.out.printf& * .getRecoveryId& * * & * deleteSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.deleteSecret * * @param name The name of the secret to be deleted. * @return A {@link SyncPoller} to poll on and retrieve the {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<DeletedSecret, Void> beginDeleteSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), deleteActivationOperation(name), deletePollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deleteActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createDeletedSecret(implClient.deleteSecret(vaultUrl, name))), SecretAsyncClient::mapDeleteSecretException); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deletePollOperation(String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createDeletedSecret(implClient.getDeletedSecret(vaultUrl, name))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecret * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecret * * @param name The name of the deleted secret. * @return The {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public DeletedSecret getDeletedSecret(String name) { return getDeletedSecretWithResponse(name, Context.NONE).getValue(); } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * * @param name The name of the deleted secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<DeletedSecret> getDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<DeletedSecretBundle> response = implClient.getDeletedSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, createDeletedSecret(response.getValue())); }, SecretAsyncClient::mapGetDeletedSecretException); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecret * <pre> * secretClient.purgeDeletedSecret& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecret * * @param name The name of the secret. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public void purgeDeletedSecret(String name) { purgeDeletedSecretWithResponse(name, Context.NONE); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * <pre> * Response&lt;Void&gt; purgeResponse = secretClient.purgeDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> purgeDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> implClient.purgeDeletedSecretWithResponse(vaultUrl, name, context), SecretAsyncClient::mapPurgeDeletedSecretException); } /** * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a <b>soft-delete * enabled</b> vault. This operation requires the {@code secrets/recover} permission. * * <p><strong>Code sample</strong></p> * <p>Recovers the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the details of the * recovered secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.recoverDeletedSecret * <pre> * SyncPoller&lt;KeyVaultSecret, Void&gt; recoverSecretPoller = * secretClient.beginRecoverDeletedSecret& * * & * PollResponse&lt;KeyVaultSecret&gt; recoveredSecretPollResponse = recoverSecretPoller.poll& * System.out.println& * System.out.printf& * * & * recoverSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.recoverDeletedSecret * * @param name The name of the deleted secret to be recovered. * @return A {@link SyncPoller} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<KeyVaultSecret, Void> beginRecoverDeletedSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), recoverActivationOperation(name), recoverPollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createKeyVaultSecret(implClient.recoverDeletedSecret(vaultUrl, name))), SecretAsyncClient::mapRecoverDeletedSecretException); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverPollOperation( String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createKeyVaultSecret(implClient.getSecret(vaultUrl, name, null))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecret * <pre> * byte[] secretBackup = secretClient.backupSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecret * * @param name The name of the secret. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public byte[] backupSecret(String name) { return backupSecretWithResponse(name, Context.NONE).getValue(); } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecretWithResponse * <pre> * byte[] secretBackup = secretClient.backupSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<byte[]> backupSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<BackupSecretResult> response = implClient.backupSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, response.getValue().getValue()); }, SecretAsyncClient::mapBackupSecretException); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecret * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecret * * @param backup The backup blob associated with the secret. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret restoreSecretBackup(byte[] backup) { return restoreSecretBackupWithResponse(backup, Context.NONE).getValue(); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse& * new Context& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * * @param backup The backup blob associated with the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> restoreSecretBackupWithResponse(byte[] backup, Context context) { return callWithMappedException(() -> { Response<SecretBundle> response = implClient.restoreSecretWithResponse(vaultUrl, backup, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapRestoreSecretException); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate through secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets --> * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} by page and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * <pre> * secretClient.listPropertiesOfSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. The * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets() { return listPropertiesOfSecrets(Context.NONE); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets(Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretsSinglePage(vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretsNextSinglePage(continuationToken, vaultUrl, context))); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>Iterate over Lists the deleted secrets by page in the key vault and for each deleted secret prints out its * recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * <pre> * secretClient.listDeletedSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * System.out.printf& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets() { return listDeletedSecrets(Context.NONE); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets(Context context) { return new PagedIterable<>(maxResults -> mapDeletedSecretItemPage(implClient.getDeletedSecretsSinglePage( vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapDeletedSecretItemPage(implClient.getDeletedSecretsNextSinglePage( continuationToken, vaultUrl, context))); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name) { return listPropertiesOfSecretVersions(name, Context.NONE); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * .listPropertiesOfSecretVersions& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * <p><strong>Iterate over secret versions by page</strong></p> * <p>The sample below iterates over each {@link SecretProperties secret} by each page and calls * {@link SecretClient * corresponding version's value.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * secretClient.listPropertiesOfSecretVersions& * .iterableByPage& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name, Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretVersionsSinglePage(vaultUrl, name, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretVersionsNextSinglePage( continuationToken, vaultUrl, context))); } private static <T> T callWithMappedException(Supplier<T> call, Function<KeyVaultErrorException, HttpResponseException> exceptionMapper) { try { return call.get(); } catch (KeyVaultErrorException ex) { throw exceptionMapper.apply(ex); } } }
class SecretClient { private static final ClientLogger LOGGER = new ClientLogger(SecretClient.class); private final SecretClientImpl implClient; private final String vaultUrl; /** * Gets the vault endpoint url to which service requests are sent to. * @return the vault endpoint url. */ public String getVaultUrl() { return vaultUrl; } /** * Creates a SecretClient to service requests * * @param implClient the implementation client. * @param vaultUrl the vault url. */ SecretClient(SecretClientImpl implClient, String vaultUrl) { this.implClient = implClient; this.vaultUrl = vaultUrl; } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p>The {@link SecretProperties * and {@link SecretProperties * If not specified, {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret returnedSecret = secretClient.setSecret& * System.out.printf& * returnedSecret.getValue& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret * @return The {@link KeyVaultSecret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpResponseException if {@link KeyVaultSecret * is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(KeyVaultSecret secret) { return setSecretWithResponse(secret, Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret secret = secretClient.setSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. * @return The {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(String name, String value) { return setSecretWithResponse(new KeyVaultSecret(name, value), Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecretWithResponse * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret secret = secretClient.setSecretWithResponse& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecretWithResponse * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> setSecretWithResponse(KeyVaultSecret secret, Context context) { return callWithMappedException(() -> { SecretProperties secretProperties = secret.getProperties(); if (secretProperties == null) { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), null, ContentType.APPLICATION_JSON, null, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } else { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), secretProperties.getTags(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } }, SecretAsyncClient::mapSetSecretException); } /** * Gets the latest version of the specified secret from the key vault. * This operation requires the {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * KeyVaultSecret secretWithoutVersion = secretClient.getSecret& * System.out.printf& * secretWithoutVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret. * @return The requested {@link KeyVaultSecret}. * @throws ResourceNotFoundException When a secret with the given {@code name} doesn't exist in the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. * @throws HttpResponseException If the server reports an error when executing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name) { return getSecretWithResponse(name, null, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecret& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this call is * equivalent to calling {@link * @return The requested {@link KeyVaultSecret secret}. * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in * the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. * @throws HttpResponseException If the server reports an error when executing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name, String version) { return getSecretWithResponse(name, version, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecretWithResponse * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse& * new Context& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecretWithResponse * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent * to calling {@link * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in * the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key * vault.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretProperties * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretProperties = secretClient.updateSecretProperties& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretProperties * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @return The {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public SecretProperties updateSecretProperties(SecretProperties secretProperties) { return updateSecretPropertiesWithResponse(secretProperties, Context.NONE).getValue(); } /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key vault. * </p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse& * new Context& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<SecretProperties> updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { Response<SecretBundle> response = implClient.updateSecretWithResponse(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), secretProperties.getTags(), context); return new SimpleResponse<>(response, createSecretProperties(response.getValue())); } /** * Deletes a secret from the key vault. If soft-delete is enabled on the key vault then the secret is placed in the * deleted state and for permanent deletion, needs to be purged. Otherwise, the secret is permanently deleted. * All versions of a secret are deleted. This cannot be applied to individual versions of a secret. * This operation requires the {@code secrets/delete} permission. * * <p><strong>Code sample</strong></p> * <p>Deletes the secret from a soft-delete enabled key vault. Prints out the recovery id of the deleted secret * returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.deleteSecret * <pre> * SyncPoller&lt;DeletedSecret, Void&gt; deleteSecretPoller = secretClient.beginDeleteSecret& * * & * PollResponse&lt;DeletedSecret&gt; deleteSecretPollResponse = deleteSecretPoller.poll& * * & * System.out.println& * .getDeletedOn& * System.out.printf& * .getRecoveryId& * * & * deleteSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.deleteSecret * * @param name The name of the secret to be deleted. * @return A {@link SyncPoller} to poll on and retrieve the {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<DeletedSecret, Void> beginDeleteSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), deleteActivationOperation(name), deletePollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deleteActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createDeletedSecret(implClient.deleteSecret(vaultUrl, name))), SecretAsyncClient::mapDeleteSecretException); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deletePollOperation(String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createDeletedSecret(implClient.getDeletedSecret(vaultUrl, name))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecret * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecret * * @param name The name of the deleted secret. * @return The {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public DeletedSecret getDeletedSecret(String name) { return getDeletedSecretWithResponse(name, Context.NONE).getValue(); } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * * @param name The name of the deleted secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<DeletedSecret> getDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<DeletedSecretBundle> response = implClient.getDeletedSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, createDeletedSecret(response.getValue())); }, SecretAsyncClient::mapGetDeletedSecretException); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecret * <pre> * secretClient.purgeDeletedSecret& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecret * * @param name The name of the secret. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public void purgeDeletedSecret(String name) { purgeDeletedSecretWithResponse(name, Context.NONE); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * <pre> * Response&lt;Void&gt; purgeResponse = secretClient.purgeDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> purgeDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> implClient.purgeDeletedSecretWithResponse(vaultUrl, name, context), SecretAsyncClient::mapPurgeDeletedSecretException); } /** * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a <b>soft-delete * enabled</b> vault. This operation requires the {@code secrets/recover} permission. * * <p><strong>Code sample</strong></p> * <p>Recovers the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the details of the * recovered secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.recoverDeletedSecret * <pre> * SyncPoller&lt;KeyVaultSecret, Void&gt; recoverSecretPoller = * secretClient.beginRecoverDeletedSecret& * * & * PollResponse&lt;KeyVaultSecret&gt; recoveredSecretPollResponse = recoverSecretPoller.poll& * System.out.println& * System.out.printf& * * & * recoverSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.recoverDeletedSecret * * @param name The name of the deleted secret to be recovered. * @return A {@link SyncPoller} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<KeyVaultSecret, Void> beginRecoverDeletedSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), recoverActivationOperation(name), recoverPollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createKeyVaultSecret(implClient.recoverDeletedSecret(vaultUrl, name))), SecretAsyncClient::mapRecoverDeletedSecretException); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverPollOperation( String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createKeyVaultSecret(implClient.getSecret(vaultUrl, name, null))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecret * <pre> * byte[] secretBackup = secretClient.backupSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecret * * @param name The name of the secret. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public byte[] backupSecret(String name) { return backupSecretWithResponse(name, Context.NONE).getValue(); } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecretWithResponse * <pre> * byte[] secretBackup = secretClient.backupSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<byte[]> backupSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<BackupSecretResult> response = implClient.backupSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, response.getValue().getValue()); }, SecretAsyncClient::mapBackupSecretException); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecret * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecret * * @param backup The backup blob associated with the secret. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret restoreSecretBackup(byte[] backup) { return restoreSecretBackupWithResponse(backup, Context.NONE).getValue(); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse& * new Context& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * * @param backup The backup blob associated with the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> restoreSecretBackupWithResponse(byte[] backup, Context context) { return callWithMappedException(() -> { Response<SecretBundle> response = implClient.restoreSecretWithResponse(vaultUrl, backup, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapRestoreSecretException); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate through secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets --> * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} by page and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * <pre> * secretClient.listPropertiesOfSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. The * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets() { return listPropertiesOfSecrets(Context.NONE); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets(Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretsSinglePage(vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretsNextSinglePage(continuationToken, vaultUrl, context))); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>Iterate over Lists the deleted secrets by page in the key vault and for each deleted secret prints out its * recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * <pre> * secretClient.listDeletedSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * System.out.printf& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets() { return listDeletedSecrets(Context.NONE); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets(Context context) { return new PagedIterable<>(maxResults -> mapDeletedSecretItemPage(implClient.getDeletedSecretsSinglePage( vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapDeletedSecretItemPage(implClient.getDeletedSecretsNextSinglePage( continuationToken, vaultUrl, context))); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name) { return listPropertiesOfSecretVersions(name, Context.NONE); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * .listPropertiesOfSecretVersions& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * <p><strong>Iterate over secret versions by page</strong></p> * <p>The sample below iterates over each {@link SecretProperties secret} by each page and calls * {@link SecretClient * corresponding version's value.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * secretClient.listPropertiesOfSecretVersions& * .iterableByPage& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name, Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretVersionsSinglePage(vaultUrl, name, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretVersionsNextSinglePage( continuationToken, vaultUrl, context))); } private static <T> T callWithMappedException(Supplier<T> call, Function<KeyVaultErrorException, HttpResponseException> exceptionMapper) { try { return call.get(); } catch (KeyVaultErrorException ex) { throw exceptionMapper.apply(ex); } } }
Reverting this change to have it be done in another PR where it can be discussed more directly.
public Response<KeyVaultSecret> getSecretWithResponse(String name, String version, Context context) { Objects.requireNonNull(name, "Secret name cannot be null."); return callWithMappedException(() -> { Response<SecretBundle> response = implClient.getSecretWithResponse(vaultUrl, name, version, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapGetSecretException); }
Objects.requireNonNull(name, "Secret name cannot be null.");
public Response<KeyVaultSecret> getSecretWithResponse(String name, String version, Context context) { if (CoreUtils.isNullOrEmpty(name)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'name' cannot be null or empty.")); } return callWithMappedException(() -> { Response<SecretBundle> response = implClient.getSecretWithResponse(vaultUrl, name, version, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapGetSecretException); }
class SecretClient { private final SecretClientImpl implClient; private final String vaultUrl; /** * Gets the vault endpoint url to which service requests are sent to. * @return the vault endpoint url. */ public String getVaultUrl() { return vaultUrl; } /** * Creates a SecretClient to service requests * * @param implClient the implementation client. * @param vaultUrl the vault url. */ SecretClient(SecretClientImpl implClient, String vaultUrl) { this.implClient = implClient; this.vaultUrl = vaultUrl; } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p>The {@link SecretProperties * and {@link SecretProperties * If not specified, {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret returnedSecret = secretClient.setSecret& * System.out.printf& * returnedSecret.getValue& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret * @return The {@link KeyVaultSecret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpResponseException if {@link KeyVaultSecret * is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(KeyVaultSecret secret) { return setSecretWithResponse(secret, Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret secret = secretClient.setSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. * @return The {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(String name, String value) { return setSecretWithResponse(new KeyVaultSecret(name, value), Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecretWithResponse * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret secret = secretClient.setSecretWithResponse& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecretWithResponse * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> setSecretWithResponse(KeyVaultSecret secret, Context context) { return callWithMappedException(() -> { SecretProperties secretProperties = secret.getProperties(); if (secretProperties == null) { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), null, ContentType.APPLICATION_JSON, null, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } else { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), secretProperties.getTags(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } }, SecretAsyncClient::mapSetSecretException); } /** * Gets the latest version of the specified secret from the key vault. * This operation requires the {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * KeyVaultSecret secretWithoutVersion = secretClient.getSecret& * System.out.printf& * secretWithoutVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret. * @return The requested {@link KeyVaultSecret}. * @throws NullPointerException if {@code name} is {@code null}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name) { return getSecretWithResponse(name, null, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecret& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this call is * equivalent to calling {@link * @return The requested {@link KeyVaultSecret secret}. * @throws NullPointerException if {@code name} is {@code null}. * @throws ResourceNotFoundException when a secret with {@code name} and {@code version} doesn't exist in the key * vault. * @throws HttpResponseException if {@code name} and {@code version} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name, String version) { return getSecretWithResponse(name, version, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecretWithResponse * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse& * new Context& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecretWithResponse * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent * to calling {@link * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws NullPointerException if {@code name} is {@code null}. * @throws ResourceNotFoundException when a secret with {@code name} and {@code version} doesn't exist in the key * vault. * @throws HttpResponseException if {@code name} and {@code version} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key * vault.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretProperties * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretProperties = secretClient.updateSecretProperties& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretProperties * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @return The {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public SecretProperties updateSecretProperties(SecretProperties secretProperties) { return updateSecretPropertiesWithResponse(secretProperties, Context.NONE).getValue(); } /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key vault. * </p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse& * new Context& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<SecretProperties> updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { Response<SecretBundle> response = implClient.updateSecretWithResponse(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), secretProperties.getTags(), context); return new SimpleResponse<>(response, createSecretProperties(response.getValue())); } /** * Deletes a secret from the key vault. If soft-delete is enabled on the key vault then the secret is placed in the * deleted state and for permanent deletion, needs to be purged. Otherwise, the secret is permanently deleted. * All versions of a secret are deleted. This cannot be applied to individual versions of a secret. * This operation requires the {@code secrets/delete} permission. * * <p><strong>Code sample</strong></p> * <p>Deletes the secret from a soft-delete enabled key vault. Prints out the recovery id of the deleted secret * returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.deleteSecret * <pre> * SyncPoller&lt;DeletedSecret, Void&gt; deleteSecretPoller = secretClient.beginDeleteSecret& * * & * PollResponse&lt;DeletedSecret&gt; deleteSecretPollResponse = deleteSecretPoller.poll& * * & * System.out.println& * .getDeletedOn& * System.out.printf& * .getRecoveryId& * * & * deleteSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.deleteSecret * * @param name The name of the secret to be deleted. * @return A {@link SyncPoller} to poll on and retrieve the {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<DeletedSecret, Void> beginDeleteSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), deleteActivationOperation(name), deletePollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deleteActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createDeletedSecret(implClient.deleteSecret(vaultUrl, name))), SecretAsyncClient::mapDeleteSecretException); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deletePollOperation(String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createDeletedSecret(implClient.getDeletedSecret(vaultUrl, name))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecret * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecret * * @param name The name of the deleted secret. * @return The {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public DeletedSecret getDeletedSecret(String name) { return getDeletedSecretWithResponse(name, Context.NONE).getValue(); } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * * @param name The name of the deleted secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<DeletedSecret> getDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<DeletedSecretBundle> response = implClient.getDeletedSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, createDeletedSecret(response.getValue())); }, SecretAsyncClient::mapGetDeletedSecretException); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecret * <pre> * secretClient.purgeDeletedSecret& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecret * * @param name The name of the secret. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public void purgeDeletedSecret(String name) { purgeDeletedSecretWithResponse(name, Context.NONE); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * <pre> * Response&lt;Void&gt; purgeResponse = secretClient.purgeDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> purgeDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> implClient.purgeDeletedSecretWithResponse(vaultUrl, name, context), SecretAsyncClient::mapPurgeDeletedSecretException); } /** * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a <b>soft-delete * enabled</b> vault. This operation requires the {@code secrets/recover} permission. * * <p><strong>Code sample</strong></p> * <p>Recovers the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the details of the * recovered secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.recoverDeletedSecret * <pre> * SyncPoller&lt;KeyVaultSecret, Void&gt; recoverSecretPoller = * secretClient.beginRecoverDeletedSecret& * * & * PollResponse&lt;KeyVaultSecret&gt; recoveredSecretPollResponse = recoverSecretPoller.poll& * System.out.println& * System.out.printf& * * & * recoverSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.recoverDeletedSecret * * @param name The name of the deleted secret to be recovered. * @return A {@link SyncPoller} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<KeyVaultSecret, Void> beginRecoverDeletedSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), recoverActivationOperation(name), recoverPollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createKeyVaultSecret(implClient.recoverDeletedSecret(vaultUrl, name))), SecretAsyncClient::mapRecoverDeletedSecretException); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverPollOperation( String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createKeyVaultSecret(implClient.getSecret(vaultUrl, name, null))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecret * <pre> * byte[] secretBackup = secretClient.backupSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecret * * @param name The name of the secret. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public byte[] backupSecret(String name) { return backupSecretWithResponse(name, Context.NONE).getValue(); } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecretWithResponse * <pre> * byte[] secretBackup = secretClient.backupSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<byte[]> backupSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<BackupSecretResult> response = implClient.backupSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, response.getValue().getValue()); }, SecretAsyncClient::mapBackupSecretException); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecret * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecret * * @param backup The backup blob associated with the secret. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret restoreSecretBackup(byte[] backup) { return restoreSecretBackupWithResponse(backup, Context.NONE).getValue(); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse& * new Context& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * * @param backup The backup blob associated with the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> restoreSecretBackupWithResponse(byte[] backup, Context context) { return callWithMappedException(() -> { Response<SecretBundle> response = implClient.restoreSecretWithResponse(vaultUrl, backup, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapRestoreSecretException); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate through secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets --> * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} by page and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * <pre> * secretClient.listPropertiesOfSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. The * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets() { return listPropertiesOfSecrets(Context.NONE); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets(Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretsSinglePage(vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretsNextSinglePage(continuationToken, vaultUrl, context))); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>Iterate over Lists the deleted secrets by page in the key vault and for each deleted secret prints out its * recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * <pre> * secretClient.listDeletedSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * System.out.printf& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets() { return listDeletedSecrets(Context.NONE); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets(Context context) { return new PagedIterable<>(maxResults -> mapDeletedSecretItemPage(implClient.getDeletedSecretsSinglePage( vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapDeletedSecretItemPage(implClient.getDeletedSecretsNextSinglePage( continuationToken, vaultUrl, context))); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name) { return listPropertiesOfSecretVersions(name, Context.NONE); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * .listPropertiesOfSecretVersions& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * <p><strong>Iterate over secret versions by page</strong></p> * <p>The sample below iterates over each {@link SecretProperties secret} by each page and calls * {@link SecretClient * corresponding version's value.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * secretClient.listPropertiesOfSecretVersions& * .iterableByPage& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name, Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretVersionsSinglePage(vaultUrl, name, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretVersionsNextSinglePage( continuationToken, vaultUrl, context))); } private static <T> T callWithMappedException(Supplier<T> call, Function<KeyVaultErrorException, HttpResponseException> exceptionMapper) { try { return call.get(); } catch (KeyVaultErrorException ex) { throw exceptionMapper.apply(ex); } } }
class SecretClient { private static final ClientLogger LOGGER = new ClientLogger(SecretClient.class); private final SecretClientImpl implClient; private final String vaultUrl; /** * Gets the vault endpoint url to which service requests are sent to. * @return the vault endpoint url. */ public String getVaultUrl() { return vaultUrl; } /** * Creates a SecretClient to service requests * * @param implClient the implementation client. * @param vaultUrl the vault url. */ SecretClient(SecretClientImpl implClient, String vaultUrl) { this.implClient = implClient; this.vaultUrl = vaultUrl; } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p>The {@link SecretProperties * and {@link SecretProperties * If not specified, {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret returnedSecret = secretClient.setSecret& * System.out.printf& * returnedSecret.getValue& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret * @return The {@link KeyVaultSecret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpResponseException if {@link KeyVaultSecret * is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(KeyVaultSecret secret) { return setSecretWithResponse(secret, Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecret * <pre> * KeyVaultSecret secret = secretClient.setSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecret * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. * @return The {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(String name, String value) { return setSecretWithResponse(new KeyVaultSecret(name, value), Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * * <p><strong>Code sample</strong></p> * <p>Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.setSecretWithResponse * <pre> * KeyVaultSecret newSecret = new KeyVaultSecret& * .setProperties& * KeyVaultSecret secret = secretClient.setSecretWithResponse& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.setSecretWithResponse * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> setSecretWithResponse(KeyVaultSecret secret, Context context) { return callWithMappedException(() -> { SecretProperties secretProperties = secret.getProperties(); if (secretProperties == null) { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), null, ContentType.APPLICATION_JSON, null, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } else { Response<SecretBundle> response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), secretProperties.getTags(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } }, SecretAsyncClient::mapSetSecretException); } /** * Gets the latest version of the specified secret from the key vault. * This operation requires the {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * KeyVaultSecret secretWithoutVersion = secretClient.getSecret& * System.out.printf& * secretWithoutVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret. * @return The requested {@link KeyVaultSecret}. * @throws ResourceNotFoundException When a secret with the given {@code name} doesn't exist in the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. * @throws HttpResponseException If the server reports an error when executing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name) { return getSecretWithResponse(name, null, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecret * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecret& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecret * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this call is * equivalent to calling {@link * @return The requested {@link KeyVaultSecret secret}. * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in * the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. * @throws HttpResponseException If the server reports an error when executing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name, String version) { return getSecretWithResponse(name, version, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * * <p><strong>Code sample</strong></p> * <p>Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getSecretWithResponse * <pre> * String secretVersion = &quot;6A385B124DEF4096AF1361A85B16C204&quot;; * KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse& * new Context& * System.out.printf& * secretWithVersion.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getSecretWithResponse * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent * to calling {@link * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in * the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key * vault.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretProperties * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretProperties = secretClient.updateSecretProperties& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretProperties * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @return The {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public SecretProperties updateSecretProperties(SecretProperties secretProperties) { return updateSecretPropertiesWithResponse(secretProperties, Context.NONE).getValue(); } /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * * <p>The {@code secret} is required and its fields {@link SecretProperties * {@link SecretProperties * * <p><strong>Code sample</strong></p> * <p>Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key vault. * </p> * <!-- src_embed com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * <pre> * SecretProperties secretProperties = secretClient.getSecret& * secretProperties.setExpiresOn& * SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse& * new Context& * KeyVaultSecret updatedSecret = secretClient.getSecret& * System.out.printf& * updatedSecret.getName& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties * {@link SecretProperties * @throws HttpResponseException if {@link SecretProperties * {@link SecretProperties */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<SecretProperties> updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { Response<SecretBundle> response = implClient.updateSecretWithResponse(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), ContentType.APPLICATION_JSON, createSecretAttributes(secretProperties), secretProperties.getTags(), context); return new SimpleResponse<>(response, createSecretProperties(response.getValue())); } /** * Deletes a secret from the key vault. If soft-delete is enabled on the key vault then the secret is placed in the * deleted state and for permanent deletion, needs to be purged. Otherwise, the secret is permanently deleted. * All versions of a secret are deleted. This cannot be applied to individual versions of a secret. * This operation requires the {@code secrets/delete} permission. * * <p><strong>Code sample</strong></p> * <p>Deletes the secret from a soft-delete enabled key vault. Prints out the recovery id of the deleted secret * returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.deleteSecret * <pre> * SyncPoller&lt;DeletedSecret, Void&gt; deleteSecretPoller = secretClient.beginDeleteSecret& * * & * PollResponse&lt;DeletedSecret&gt; deleteSecretPollResponse = deleteSecretPoller.poll& * * & * System.out.println& * .getDeletedOn& * System.out.printf& * .getRecoveryId& * * & * deleteSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.deleteSecret * * @param name The name of the secret to be deleted. * @return A {@link SyncPoller} to poll on and retrieve the {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<DeletedSecret, Void> beginDeleteSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), deleteActivationOperation(name), deletePollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deleteActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createDeletedSecret(implClient.deleteSecret(vaultUrl, name))), SecretAsyncClient::mapDeleteSecretException); } private Function<PollingContext<DeletedSecret>, PollResponse<DeletedSecret>> deletePollOperation(String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createDeletedSecret(implClient.getDeletedSecret(vaultUrl, name))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecret * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecret * * @param name The name of the deleted secret. * @return The {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public DeletedSecret getDeletedSecret(String name) { return getDeletedSecretWithResponse(name, Context.NONE).getValue(); } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Gets the deleted secret from the key vault <b>enabled for soft-delete</b>. Prints out the details of the * deleted secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * <pre> * DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse * * @param name The name of the deleted secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<DeletedSecret> getDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<DeletedSecretBundle> response = implClient.getDeletedSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, createDeletedSecret(response.getValue())); }, SecretAsyncClient::mapGetDeletedSecretException); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecret * <pre> * secretClient.purgeDeletedSecret& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecret * * @param name The name of the secret. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public void purgeDeletedSecret(String name) { purgeDeletedSecretWithResponse(name, Context.NONE); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a <b>soft-delete enabled</b> vault. This operation requires the {@code secrets/purge} permission. * * <p><strong>Code sample</strong></p> * <p>Purges the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the status code from * the server response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * <pre> * Response&lt;Void&gt; purgeResponse = secretClient.purgeDeletedSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> purgeDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> implClient.purgeDeletedSecretWithResponse(vaultUrl, name, context), SecretAsyncClient::mapPurgeDeletedSecretException); } /** * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a <b>soft-delete * enabled</b> vault. This operation requires the {@code secrets/recover} permission. * * <p><strong>Code sample</strong></p> * <p>Recovers the deleted secret from the key vault enabled for <b>soft-delete</b>. Prints out the details of the * recovered secret returned in the response.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.recoverDeletedSecret * <pre> * SyncPoller&lt;KeyVaultSecret, Void&gt; recoverSecretPoller = * secretClient.beginRecoverDeletedSecret& * * & * PollResponse&lt;KeyVaultSecret&gt; recoveredSecretPollResponse = recoverSecretPoller.poll& * System.out.println& * System.out.printf& * * & * recoverSecretPoller.waitForCompletion& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.recoverDeletedSecret * * @param name The name of the deleted secret to be recovered. * @return A {@link SyncPoller} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<KeyVaultSecret, Void> beginRecoverDeletedSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), recoverActivationOperation(name), recoverPollOperation(name), (context, response) -> null, context -> null); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createKeyVaultSecret(implClient.recoverDeletedSecret(vaultUrl, name))), SecretAsyncClient::mapRecoverDeletedSecretException); } private Function<PollingContext<KeyVaultSecret>, PollResponse<KeyVaultSecret>> recoverPollOperation( String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createKeyVaultSecret(implClient.getSecret(vaultUrl, name, null))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecret * <pre> * byte[] secretBackup = secretClient.backupSecret& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecret * * @param name The name of the secret. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public byte[] backupSecret(String name) { return backupSecretWithResponse(name, Context.NONE).getValue(); } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * * <p><strong>Code sample</strong></p> * <p>Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.backupSecretWithResponse * <pre> * byte[] secretBackup = secretClient.backupSecretWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.backupSecretWithResponse * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<byte[]> backupSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response<BackupSecretResult> response = implClient.backupSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, response.getValue().getValue()); }, SecretAsyncClient::mapBackupSecretException); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecret * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecret * * @param backup The backup blob associated with the secret. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret restoreSecretBackup(byte[] backup) { return restoreSecretBackupWithResponse(backup, Context.NONE).getValue(); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * * <p><strong>Code sample</strong></p> * <p>Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * <pre> * & * byte[] secretBackupByteArray = & * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse& * new Context& * System.out * .printf& * </pre> * <!-- end com.azure.security.keyvault.SecretClient.restoreSecretWithResponse * * @param backup The backup blob associated with the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<KeyVaultSecret> restoreSecretBackupWithResponse(byte[] backup, Context context) { return callWithMappedException(() -> { Response<SecretBundle> response = implClient.restoreSecretWithResponse(vaultUrl, backup, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapRestoreSecretException); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate through secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets --> * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} by page and calls * {@link * value of its latest version.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * <pre> * secretClient.listPropertiesOfSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage --> * * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. The * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets() { return listPropertiesOfSecrets(Context.NONE); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets and fetch their latest value</strong></p> * <p>The snippet below loops over each {@link SecretProperties secret} and calls * {@link * value of its latest version.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecrets * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecrets(Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretsSinglePage(vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretsNextSinglePage(continuationToken, vaultUrl, context))); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Iterate over secrets</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets --> * * <p><strong>Iterate over secrets by page</strong></p> * <p>Iterate over Lists the deleted secrets by page in the key vault and for each deleted secret prints out its * recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * <pre> * secretClient.listDeletedSecrets& * System.out.printf& * resp.getRequest& * resp.getItems& * System.out.printf& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage --> * * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets() { return listDeletedSecrets(Context.NONE); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listDeletedSecrets * <pre> * for & * System.out.printf& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listDeletedSecrets * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<DeletedSecret> listDeletedSecrets(Context context) { return new PagedIterable<>(maxResults -> mapDeletedSecretItemPage(implClient.getDeletedSecretsSinglePage( vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapDeletedSecretItemPage(implClient.getDeletedSecretsNextSinglePage( continuationToken, vaultUrl, context))); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name) { return listPropertiesOfSecretVersions(name, Context.NONE); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * * <p><strong>Code sample</strong></p> * <p>The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link * out.</p> * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * for & * .listPropertiesOfSecretVersions& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * <p><strong>Iterate over secret versions by page</strong></p> * <p>The sample below iterates over each {@link SecretProperties secret} by each page and calls * {@link SecretClient * corresponding version's value.</p> * * <!-- src_embed com.azure.security.keyvault.SecretClient.listSecretVersions * <pre> * secretClient.listPropertiesOfSecretVersions& * .iterableByPage& * System.out.printf& * resp.getRequest& * resp.getItems& * KeyVaultSecret secretWithValue = secretClient.getSecret& * System.out.printf& * secretWithValue.getName& * & * & * </pre> * <!-- end com.azure.security.keyvault.SecretClient.listSecretVersions * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SecretProperties> listPropertiesOfSecretVersions(String name, Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretVersionsSinglePage(vaultUrl, name, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretVersionsNextSinglePage( continuationToken, vaultUrl, context))); } private static <T> T callWithMappedException(Supplier<T> call, Function<KeyVaultErrorException, HttpResponseException> exceptionMapper) { try { return call.get(); } catch (KeyVaultErrorException ex) { throw exceptionMapper.apply(ex); } } }
```suggestion "Only 1 overload for initialPartitionEventPosition can be set. The overload is set " ```
public EventProcessorClient buildEventProcessorClient() { Objects.requireNonNull(processError, "'processError' cannot be null"); Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); if (processEvent == null && processEventBatch == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Either processEvent or processEventBatch " + "has to be set")); } if (processEvent != null && processEventBatch != null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Both processEvent and processEventBatch " + "cannot be set")); } if (loadBalancingUpdateInterval == null) { loadBalancingUpdateInterval = DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL; } if (partitionOwnershipExpirationInterval == null) { partitionOwnershipExpirationInterval = DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL; } final EventProcessorClientOptions processorOptions = new EventProcessorClientOptions() .setConsumerGroup(consumerGroup) .setBatchReceiveMode(processEventBatch != null) .setConsumerGroup(consumerGroup) .setLoadBalancingStrategy(loadBalancingStrategy) .setLoadBalancerUpdateInterval(loadBalancingUpdateInterval) .setMaxBatchSize(maxBatchSize) .setMaxWaitTime(maxWaitTime) .setPartitionOwnershipExpirationInterval(partitionOwnershipExpirationInterval) .setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties); int numberOfTimesSet = 0; if (defaultInitialEventPosition != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider(unused -> defaultInitialEventPosition); } if (initialPartitionEventPosition != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider( partitionId -> initialPartitionEventPosition.get(partitionId)); } if (initialEventPositionProvider != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider(initialEventPositionProvider); } if (numberOfTimesSet > 1) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Only 1 overload for setInitialEventPositionProvider can be set. The overload is set " + numberOfTimesSet + " times.")); } return new EventProcessorClient(eventHubClientBuilder, getPartitionProcessorSupplier(), checkpointStore, processError, eventHubClientBuilder.createTracer(), processorOptions); }
"Only 1 overload for setInitialEventPositionProvider can be set. The overload is set "
public EventProcessorClient buildEventProcessorClient() { Objects.requireNonNull(processError, "'processError' cannot be null"); Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); if (processEvent == null && processEventBatch == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Either processEvent or processEventBatch " + "has to be set")); } if (processEvent != null && processEventBatch != null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Both processEvent and processEventBatch " + "cannot be set")); } if (loadBalancingUpdateInterval == null) { loadBalancingUpdateInterval = DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL; } if (partitionOwnershipExpirationInterval == null) { partitionOwnershipExpirationInterval = DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL; } final EventProcessorClientOptions processorOptions = new EventProcessorClientOptions() .setConsumerGroup(consumerGroup) .setBatchReceiveMode(processEventBatch != null) .setConsumerGroup(consumerGroup) .setLoadBalancingStrategy(loadBalancingStrategy) .setLoadBalancerUpdateInterval(loadBalancingUpdateInterval) .setMaxBatchSize(maxBatchSize) .setMaxWaitTime(maxWaitTime) .setPartitionOwnershipExpirationInterval(partitionOwnershipExpirationInterval) .setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties); int numberOfTimesSet = 0; if (initialPartitionEventPosition != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider( partitionId -> initialPartitionEventPosition.get(partitionId)); } if (initialEventPositionProvider != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider(initialEventPositionProvider); } if (numberOfTimesSet > 1) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Only 1 overload for initialEventPositionProvider can be set. The overload is set " + numberOfTimesSet + " times.")); } return new EventProcessorClient(eventHubClientBuilder, getPartitionProcessorSupplier(), checkpointStore, processError, eventHubClientBuilder.createTracer(), processorOptions); }
class EventProcessorClientBuilder implements TokenCredentialTrait<EventProcessorClientBuilder>, AzureNamedKeyCredentialTrait<EventProcessorClientBuilder>, ConnectionStringTrait<EventProcessorClientBuilder>, AzureSasCredentialTrait<EventProcessorClientBuilder>, AmqpTrait<EventProcessorClientBuilder>, ConfigurationTrait<EventProcessorClientBuilder> { /** * Default load balancing update interval. Balancing interval should account for latency between the client and the * storage account. */ public static final Duration DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL = Duration.ofSeconds(30); /** * Default ownership expiration. */ public static final Duration DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL = Duration.ofMinutes(2); private static final ClientLogger LOGGER = new ClientLogger(EventProcessorClientBuilder.class); private final EventHubClientBuilder eventHubClientBuilder; private String consumerGroup; private CheckpointStore checkpointStore; private Consumer<EventContext> processEvent; private Consumer<EventBatchContext> processEventBatch; private Consumer<ErrorContext> processError; private Consumer<InitializationContext> processPartitionInitialization; private Consumer<CloseContext> processPartitionClose; private boolean trackLastEnqueuedEventProperties; private Map<String, EventPosition> initialPartitionEventPosition = null; private int maxBatchSize = 1; private Duration maxWaitTime; private Duration loadBalancingUpdateInterval; private Duration partitionOwnershipExpirationInterval; private LoadBalancingStrategy loadBalancingStrategy = LoadBalancingStrategy.GREEDY; private EventPosition defaultInitialEventPosition = null; private Function<String, EventPosition> initialEventPositionProvider; /** * Creates a new instance of {@link EventProcessorClientBuilder}. */ public EventProcessorClientBuilder() { eventHubClientBuilder = new EventHubClientBuilder(); } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventProcessorClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { eventHubClientBuilder.fullyQualifiedNamespace(fullyQualifiedNamespace); return this; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventProcessorClientBuilder eventHubName(String eventHubName) { eventHubClientBuilder.eventHubName(eventHubName); return this; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding * {@literal "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, * "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} is {@code null}. * @throws IllegalArgumentException if {@code connectionString} is empty. Or, the {@code connectionString} does * not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventProcessorClientBuilder connectionString(String connectionString) { eventHubClientBuilder.connectionString(connectionString); return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventProcessorClientBuilder connectionString(String connectionString, String eventHubName) { eventHubClientBuilder.connectionString(connectionString, eventHubName); return this; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder configuration(Configuration configuration) { eventHubClientBuilder.configuration(configuration); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credential} is null. */ @Override public EventProcessorClientBuilder credential(TokenCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureSasCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through an * intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventProcessorClientBuilder customEndpointAddress(String customEndpointAddress) { eventHubClientBuilder.customEndpointAddress(customEndpointAddress); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, * {@link AmqpTransportType * * @param proxyOptions The proxy options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder proxyOptions(ProxyOptions proxyOptions) { eventHubClientBuilder.proxyOptions(proxyOptions); return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is * {@link AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder transportType(AmqpTransportType transport) { eventHubClientBuilder.transportType(transport); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventProcessorClientBuilder} object. * * @deprecated Replaced by {@link */ @Deprecated public EventProcessorClientBuilder retry(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder retryOptions(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the client options for the processor client. The application id set on the client options will be used for * tracing. The headers set on {@code ClientOptions} are currently not used but can be used in later releases to add * to AMQP message. * * @param clientOptions The client options. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder clientOptions(ClientOptions clientOptions) { eventHubClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the consumer group name from which the {@link EventProcessorClient} should consume events. * * @param consumerGroup The consumer group name this {@link EventProcessorClient} should consume events. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code consumerGroup} is {@code null}. */ public EventProcessorClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); return this; } /** * Sets the {@link CheckpointStore} the {@link EventProcessorClient} will use for storing partition ownership and * checkpoint information. * * <p> * Users can, optionally, provide their own implementation of {@link CheckpointStore} which will store ownership and * checkpoint information. * </p> * * @param checkpointStore Implementation of {@link CheckpointStore}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code checkpointStore} is {@code null}. */ public EventProcessorClientBuilder checkpointStore(CheckpointStore checkpointStore) { this.checkpointStore = Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); return this; } /** * The time interval between load balancing update cycles. This is also generally the interval at which ownership of * partitions are renewed. By default, this interval is set to 10 seconds. * * @param loadBalancingUpdateInterval The time duration between load balancing update cycles. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingUpdateInterval} is {@code null}. * @throws IllegalArgumentException if {@code loadBalancingUpdateInterval} is zero or a negative duration. */ public EventProcessorClientBuilder loadBalancingUpdateInterval(Duration loadBalancingUpdateInterval) { Objects.requireNonNull(loadBalancingUpdateInterval, "'loadBalancingUpdateInterval' cannot be null"); if (loadBalancingUpdateInterval.isZero() || loadBalancingUpdateInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'loadBalancingUpdateInterval' " + "should be a positive duration")); } this.loadBalancingUpdateInterval = loadBalancingUpdateInterval; return this; } /** * The time duration after which the ownership of partition expires if it's not renewed by the owning processor * instance. This is the duration that this processor instance will wait before taking over the ownership of * partitions previously owned by an inactive processor. By default, this duration is set to a minute. * * @param partitionOwnershipExpirationInterval The time duration after which the ownership of partition * expires. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code partitionOwnershipExpirationInterval} is {@code null}. * @throws IllegalArgumentException if {@code partitionOwnershipExpirationInterval} is zero or a negative * duration. */ public EventProcessorClientBuilder partitionOwnershipExpirationInterval( Duration partitionOwnershipExpirationInterval) { Objects.requireNonNull(partitionOwnershipExpirationInterval, "'partitionOwnershipExpirationInterval' cannot " + "be null"); if (partitionOwnershipExpirationInterval.isZero() || partitionOwnershipExpirationInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'partitionOwnershipExpirationInterval' " + "should be a positive duration")); } this.partitionOwnershipExpirationInterval = partitionOwnershipExpirationInterval; return this; } /** * The {@link LoadBalancingStrategy} the {@link EventProcessorClient event processor} will use for claiming * partition ownership. By default, a {@link LoadBalancingStrategy * * @param loadBalancingStrategy The {@link LoadBalancingStrategy} to use. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingStrategy} is {@code null}. */ public EventProcessorClientBuilder loadBalancingStrategy(LoadBalancingStrategy loadBalancingStrategy) { this.loadBalancingStrategy = Objects.requireNonNull(loadBalancingStrategy, "'loadBalancingStrategy' cannot be" + " null"); return this; } /** * Sets the count used by the receivers to control the number of events each consumer will actively receive and * queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The number of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * * @throws IllegalArgumentException if {@code prefetchCount} is less than 1 or greater than 8000. */ public EventProcessorClientBuilder prefetchCount(int prefetchCount) { eventHubClientBuilder.prefetchCount(prefetchCount); return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. * * @param processEvent The callback that's called when an event is received by this * {@link EventProcessorClient}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent) { return this.processEvent(processEvent, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEvent The callback that's called when an event is received by this {@link EventProcessorClient} * or when the max wait duration has expired. * @param maxWaitTime The max time duration to wait to receive an event before invoking this handler. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent, Duration maxWaitTime) { this.processEvent = Objects.requireNonNull(processEvent, "'processEvent' cannot be null"); if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEventBatch The callback that's called when an event is received by this * {@link EventProcessorClient} or when the max wait duration has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize) { return this.processEventBatch(processEventBatch, maxBatchSize, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * <!-- src_embed com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * <pre> * TokenCredential credential = new DefaultAzureCredentialBuilder& * * & * & * EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder& * .consumerGroup& * .checkpointStore& * .processEventBatch& * eventBatchContext.getEvents& * System.out.printf& * eventBatchContext.getPartitionContext& * eventData.getSequenceNumber& * & * & * .processError& * System.out.printf& * errorContext.getPartitionContext& * errorContext.getThrowable& * & * .buildEventProcessorClient& * </pre> * <!-- end com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * * @param processEventBatch The callback that's called when an event is received or when the max wait duration * has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * @param maxWaitTime The max time duration to wait to receive a batch of events upto the max batch size before * invoking this callback. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize, Duration maxWaitTime) { if (maxBatchSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxBatchSize' should be greater than 0")); } if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.processEventBatch = Objects.requireNonNull(processEventBatch, "'processEventBatch' cannot be null"); this.maxBatchSize = maxBatchSize; this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called when an error occurs while processing events. The input contains the partition * information where the error happened. * * @param processError The callback that's called when an error occurs while processing events. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processError(Consumer<ErrorContext> processError) { this.processError = processError; return this; } /** * The function that is called before processing starts for a partition. The input contains the partition * information along with a default starting position for processing events that will be used in the case of a * checkpoint unavailable in {@link CheckpointStore}. Users can update this position if a different starting * position is preferred. * * @param initializePartition The callback that's called before processing starts for a partition * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionInitialization( Consumer<InitializationContext> initializePartition) { this.processPartitionInitialization = initializePartition; return this; } /** * The function that is called when a processing for a partition stops. The input contains the partition information * along with the reason for stopping the event processing for this partition. * * @param closePartition The callback that's called after processing for a partition stops. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionClose(Consumer<CloseContext> closePartition) { this.processPartitionClose = closePartition; return this; } /** * Sets whether or not the event processor should request information on the last enqueued event on its associated * partition, and track that information as events are received. * * <p>When information about the partition's last enqueued event is being tracked, each event received from the * Event Hubs service will carry metadata about the partition that it otherwise would not. This results in a small * amount of additional network bandwidth consumption that is generally a favorable trade-off when considered * against periodically making requests for partition properties using the Event Hub client.</p> * * @param trackLastEnqueuedEventProperties {@code true} if the resulting events will keep track of the last * enqueued information for that partition; {@code false} otherwise. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder trackLastEnqueuedEventProperties(boolean trackLastEnqueuedEventProperties) { this.trackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties; return this; } /** * Sets the default starting position for each partition if a checkpoint for that partition does not exist in the * {@link CheckpointStore}. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialEventPosition Event position to start reading events. Applies to every partition in the Event Hub * without a checkpoint nor an entry in the {@link * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition(EventPosition initialEventPosition) { this.defaultInitialEventPosition = initialEventPosition; return this; } /** * Sets the map containing the event position to use for each partition if a checkpoint for the partition does not * exist in {@link CheckpointStore}. This map is keyed off of the partition id. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialPartitionEventPosition Map of initial event positions for partition ids. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition( Map<String, EventPosition> initialPartitionEventPosition) { this.initialPartitionEventPosition = Objects.requireNonNull(initialPartitionEventPosition, "'initialPartitionEventPosition' cannot be null."); return this; } /** * Sets the default starting position for each partition if a checkpoint for that partition does not exist in the * {@link CheckpointStore}. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialEventPositionProvider Function that maps the given {@code partitionId} to an * {@link EventPosition}. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition( Function<String, EventPosition> initialEventPositionProvider) { this.initialEventPositionProvider = initialEventPositionProvider; return this; } /** * This will create a new {@link EventProcessorClient} configured with the options set in this builder. Each call to * this method will return a new instance of {@link EventProcessorClient}. * * <p> * All partitions processed by this {@link EventProcessorClient} will start processing from * {@link EventPosition * </p> * * @return A new instance of {@link EventProcessorClient}. * * @throws NullPointerException if {@code processEvent} or {@code processError} or {@code checkpointStore} or * {@code consumerGroup} is {@code null}. * @throws IllegalArgumentException if the credentials have not been set using either * {@link * specified but the transport type is not {@link AmqpTransportType * than one overload for {@code setInitialEventPositionProvider} is set. */ private Supplier<PartitionProcessor> getPartitionProcessorSupplier() { return () -> new PartitionProcessor() { @Override public void processEvent(EventContext eventContext) { if (processEvent != null) { processEvent.accept(eventContext); } } @Override public void processEventBatch(EventBatchContext eventBatchContext) { if (processEventBatch != null) { processEventBatch.accept(eventBatchContext); } else { super.processEventBatch(eventBatchContext); } } @Override public void initialize(InitializationContext initializationContext) { if (processPartitionInitialization != null) { processPartitionInitialization.accept(initializationContext); } else { super.initialize(initializationContext); } } @Override public void processError(ErrorContext errorContext) { processError.accept(errorContext); } @Override public void close(CloseContext closeContext) { if (processPartitionClose != null) { processPartitionClose.accept(closeContext); } else { super.close(closeContext); } } }; } }
class EventProcessorClientBuilder implements TokenCredentialTrait<EventProcessorClientBuilder>, AzureNamedKeyCredentialTrait<EventProcessorClientBuilder>, ConnectionStringTrait<EventProcessorClientBuilder>, AzureSasCredentialTrait<EventProcessorClientBuilder>, AmqpTrait<EventProcessorClientBuilder>, ConfigurationTrait<EventProcessorClientBuilder> { /** * Default load balancing update interval. Balancing interval should account for latency between the client and the * storage account. */ public static final Duration DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL = Duration.ofSeconds(30); /** * Default ownership expiration. */ public static final Duration DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL = Duration.ofMinutes(2); private static final ClientLogger LOGGER = new ClientLogger(EventProcessorClientBuilder.class); private final EventHubClientBuilder eventHubClientBuilder; private String consumerGroup; private CheckpointStore checkpointStore; private Consumer<EventContext> processEvent; private Consumer<EventBatchContext> processEventBatch; private Consumer<ErrorContext> processError; private Consumer<InitializationContext> processPartitionInitialization; private Consumer<CloseContext> processPartitionClose; private boolean trackLastEnqueuedEventProperties; private Map<String, EventPosition> initialPartitionEventPosition = null; private int maxBatchSize = 1; private Duration maxWaitTime; private Duration loadBalancingUpdateInterval; private Duration partitionOwnershipExpirationInterval; private LoadBalancingStrategy loadBalancingStrategy = LoadBalancingStrategy.GREEDY; private Function<String, EventPosition> initialEventPositionProvider; /** * Creates a new instance of {@link EventProcessorClientBuilder}. */ public EventProcessorClientBuilder() { eventHubClientBuilder = new EventHubClientBuilder(); } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventProcessorClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { eventHubClientBuilder.fullyQualifiedNamespace(fullyQualifiedNamespace); return this; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventProcessorClientBuilder eventHubName(String eventHubName) { eventHubClientBuilder.eventHubName(eventHubName); return this; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding * {@literal "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, * "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} is {@code null}. * @throws IllegalArgumentException if {@code connectionString} is empty. Or, the {@code connectionString} does * not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventProcessorClientBuilder connectionString(String connectionString) { eventHubClientBuilder.connectionString(connectionString); return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventProcessorClientBuilder connectionString(String connectionString, String eventHubName) { eventHubClientBuilder.connectionString(connectionString, eventHubName); return this; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder configuration(Configuration configuration) { eventHubClientBuilder.configuration(configuration); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credential} is null. */ @Override public EventProcessorClientBuilder credential(TokenCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureSasCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through an * intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventProcessorClientBuilder customEndpointAddress(String customEndpointAddress) { eventHubClientBuilder.customEndpointAddress(customEndpointAddress); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, * {@link AmqpTransportType * * @param proxyOptions The proxy options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder proxyOptions(ProxyOptions proxyOptions) { eventHubClientBuilder.proxyOptions(proxyOptions); return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is * {@link AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder transportType(AmqpTransportType transport) { eventHubClientBuilder.transportType(transport); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventProcessorClientBuilder} object. * * @deprecated Replaced by {@link */ @Deprecated public EventProcessorClientBuilder retry(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder retryOptions(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the client options for the processor client. The application id set on the client options will be used for * tracing. The headers set on {@code ClientOptions} are currently not used but can be used in later releases to add * to AMQP message. * * @param clientOptions The client options. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder clientOptions(ClientOptions clientOptions) { eventHubClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the consumer group name from which the {@link EventProcessorClient} should consume events. * * @param consumerGroup The consumer group name this {@link EventProcessorClient} should consume events. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code consumerGroup} is {@code null}. */ public EventProcessorClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); return this; } /** * Sets the {@link CheckpointStore} the {@link EventProcessorClient} will use for storing partition ownership and * checkpoint information. * * <p> * Users can, optionally, provide their own implementation of {@link CheckpointStore} which will store ownership and * checkpoint information. * </p> * * @param checkpointStore Implementation of {@link CheckpointStore}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code checkpointStore} is {@code null}. */ public EventProcessorClientBuilder checkpointStore(CheckpointStore checkpointStore) { this.checkpointStore = Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); return this; } /** * The time interval between load balancing update cycles. This is also generally the interval at which ownership of * partitions are renewed. By default, this interval is set to 10 seconds. * * @param loadBalancingUpdateInterval The time duration between load balancing update cycles. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingUpdateInterval} is {@code null}. * @throws IllegalArgumentException if {@code loadBalancingUpdateInterval} is zero or a negative duration. */ public EventProcessorClientBuilder loadBalancingUpdateInterval(Duration loadBalancingUpdateInterval) { Objects.requireNonNull(loadBalancingUpdateInterval, "'loadBalancingUpdateInterval' cannot be null"); if (loadBalancingUpdateInterval.isZero() || loadBalancingUpdateInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'loadBalancingUpdateInterval' " + "should be a positive duration")); } this.loadBalancingUpdateInterval = loadBalancingUpdateInterval; return this; } /** * The time duration after which the ownership of partition expires if it's not renewed by the owning processor * instance. This is the duration that this processor instance will wait before taking over the ownership of * partitions previously owned by an inactive processor. By default, this duration is set to a minute. * * @param partitionOwnershipExpirationInterval The time duration after which the ownership of partition * expires. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code partitionOwnershipExpirationInterval} is {@code null}. * @throws IllegalArgumentException if {@code partitionOwnershipExpirationInterval} is zero or a negative * duration. */ public EventProcessorClientBuilder partitionOwnershipExpirationInterval( Duration partitionOwnershipExpirationInterval) { Objects.requireNonNull(partitionOwnershipExpirationInterval, "'partitionOwnershipExpirationInterval' cannot " + "be null"); if (partitionOwnershipExpirationInterval.isZero() || partitionOwnershipExpirationInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'partitionOwnershipExpirationInterval' " + "should be a positive duration")); } this.partitionOwnershipExpirationInterval = partitionOwnershipExpirationInterval; return this; } /** * The {@link LoadBalancingStrategy} the {@link EventProcessorClient event processor} will use for claiming * partition ownership. By default, a {@link LoadBalancingStrategy * * @param loadBalancingStrategy The {@link LoadBalancingStrategy} to use. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingStrategy} is {@code null}. */ public EventProcessorClientBuilder loadBalancingStrategy(LoadBalancingStrategy loadBalancingStrategy) { this.loadBalancingStrategy = Objects.requireNonNull(loadBalancingStrategy, "'loadBalancingStrategy' cannot be" + " null"); return this; } /** * Sets the count used by the receivers to control the number of events each consumer will actively receive and * queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The number of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * * @throws IllegalArgumentException if {@code prefetchCount} is less than 1 or greater than 8000. */ public EventProcessorClientBuilder prefetchCount(int prefetchCount) { eventHubClientBuilder.prefetchCount(prefetchCount); return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. * * @param processEvent The callback that's called when an event is received by this * {@link EventProcessorClient}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent) { return this.processEvent(processEvent, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEvent The callback that's called when an event is received by this {@link EventProcessorClient} * or when the max wait duration has expired. * @param maxWaitTime The max time duration to wait to receive an event before invoking this handler. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent, Duration maxWaitTime) { this.processEvent = Objects.requireNonNull(processEvent, "'processEvent' cannot be null"); if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEventBatch The callback that's called when an event is received by this * {@link EventProcessorClient} or when the max wait duration has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize) { return this.processEventBatch(processEventBatch, maxBatchSize, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * <!-- src_embed com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * <pre> * TokenCredential credential = new DefaultAzureCredentialBuilder& * * & * & * EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder& * .consumerGroup& * .checkpointStore& * .processEventBatch& * eventBatchContext.getEvents& * System.out.printf& * eventBatchContext.getPartitionContext& * eventData.getSequenceNumber& * & * & * .processError& * System.out.printf& * errorContext.getPartitionContext& * errorContext.getThrowable& * & * .buildEventProcessorClient& * </pre> * <!-- end com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * * @param processEventBatch The callback that's called when an event is received or when the max wait duration * has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * @param maxWaitTime The max time duration to wait to receive a batch of events upto the max batch size before * invoking this callback. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize, Duration maxWaitTime) { if (maxBatchSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxBatchSize' should be greater than 0")); } if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.processEventBatch = Objects.requireNonNull(processEventBatch, "'processEventBatch' cannot be null"); this.maxBatchSize = maxBatchSize; this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called when an error occurs while processing events. The input contains the partition * information where the error happened. * * @param processError The callback that's called when an error occurs while processing events. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processError(Consumer<ErrorContext> processError) { this.processError = processError; return this; } /** * The function that is called before processing starts for a partition. The input contains the partition * information along with a default starting position for processing events that will be used in the case of a * checkpoint unavailable in {@link CheckpointStore}. Users can update this position if a different starting * position is preferred. * * @param initializePartition The callback that's called before processing starts for a partition * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionInitialization( Consumer<InitializationContext> initializePartition) { this.processPartitionInitialization = initializePartition; return this; } /** * The function that is called when a processing for a partition stops. The input contains the partition information * along with the reason for stopping the event processing for this partition. * * @param closePartition The callback that's called after processing for a partition stops. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionClose(Consumer<CloseContext> closePartition) { this.processPartitionClose = closePartition; return this; } /** * Sets whether or not the event processor should request information on the last enqueued event on its associated * partition, and track that information as events are received. * * <p>When information about the partition's last enqueued event is being tracked, each event received from the * Event Hubs service will carry metadata about the partition that it otherwise would not. This results in a small * amount of additional network bandwidth consumption that is generally a favorable trade-off when considered * against periodically making requests for partition properties using the Event Hub client.</p> * * @param trackLastEnqueuedEventProperties {@code true} if the resulting events will keep track of the last * enqueued information for that partition; {@code false} otherwise. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder trackLastEnqueuedEventProperties(boolean trackLastEnqueuedEventProperties) { this.trackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties; return this; } /** * Sets the map containing the event position to use for each partition if a checkpoint for the partition does not * exist in {@link CheckpointStore}. This map is keyed off of the partition id. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialPartitionEventPosition Map of initial event positions for partition ids. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition( Map<String, EventPosition> initialPartitionEventPosition) { this.initialPartitionEventPosition = Objects.requireNonNull(initialPartitionEventPosition, "'initialPartitionEventPosition' cannot be null."); return this; } /** * Sets the default starting position for each partition if a checkpoint for that partition does not exist in the * {@link CheckpointStore}. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialEventPositionProvider Function that maps the given {@code partitionId} to an * {@link EventPosition}. * * @return The updated {@link EventProcessorClientBuilder} instance. * @throws NullPointerException if {@code initialEventPositionProvider} is null. */ public EventProcessorClientBuilder initialPartitionEventPosition( Function<String, EventPosition> initialEventPositionProvider) { this.initialEventPositionProvider = Objects.requireNonNull(initialEventPositionProvider, "'initialEventPositionProvider' cannot be null."); return this; } /** * This will create a new {@link EventProcessorClient} configured with the options set in this builder. Each call to * this method will return a new instance of {@link EventProcessorClient}. * * <p> * All partitions processed by this {@link EventProcessorClient} will start processing from * {@link EventPosition * </p> * * @return A new instance of {@link EventProcessorClient}. * * @throws NullPointerException if {@code processEvent} or {@code processError} or {@code checkpointStore} or * {@code consumerGroup} is {@code null}. * @throws IllegalArgumentException if the credentials have not been set using either * {@link * specified but the transport type is not {@link AmqpTransportType * than one overload for {@code setInitialEventPositionProvider} is set. */ private Supplier<PartitionProcessor> getPartitionProcessorSupplier() { return () -> new PartitionProcessor() { @Override public void processEvent(EventContext eventContext) { if (processEvent != null) { processEvent.accept(eventContext); } } @Override public void processEventBatch(EventBatchContext eventBatchContext) { if (processEventBatch != null) { processEventBatch.accept(eventBatchContext); } else { super.processEventBatch(eventBatchContext); } } @Override public void initialize(InitializationContext initializationContext) { if (processPartitionInitialization != null) { processPartitionInitialization.accept(initializationContext); } else { super.initialize(initializationContext); } } @Override public void processError(ErrorContext errorContext) { processError.accept(errorContext); } @Override public void close(CloseContext closeContext) { if (processPartitionClose != null) { processPartitionClose.accept(closeContext); } else { super.close(closeContext); } } }; } }
nit; just confirming the message, do we mean "Only 1 overload of 'initialPartitionEventPosition' can be set ..." given that's the overloaded public api name?
public EventProcessorClient buildEventProcessorClient() { Objects.requireNonNull(processError, "'processError' cannot be null"); Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); if (processEvent == null && processEventBatch == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Either processEvent or processEventBatch " + "has to be set")); } if (processEvent != null && processEventBatch != null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Both processEvent and processEventBatch " + "cannot be set")); } if (loadBalancingUpdateInterval == null) { loadBalancingUpdateInterval = DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL; } if (partitionOwnershipExpirationInterval == null) { partitionOwnershipExpirationInterval = DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL; } final EventProcessorClientOptions processorOptions = new EventProcessorClientOptions() .setConsumerGroup(consumerGroup) .setBatchReceiveMode(processEventBatch != null) .setConsumerGroup(consumerGroup) .setLoadBalancingStrategy(loadBalancingStrategy) .setLoadBalancerUpdateInterval(loadBalancingUpdateInterval) .setMaxBatchSize(maxBatchSize) .setMaxWaitTime(maxWaitTime) .setPartitionOwnershipExpirationInterval(partitionOwnershipExpirationInterval) .setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties); int numberOfTimesSet = 0; if (defaultInitialEventPosition != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider(unused -> defaultInitialEventPosition); } if (initialPartitionEventPosition != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider( partitionId -> initialPartitionEventPosition.get(partitionId)); } if (initialEventPositionProvider != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider(initialEventPositionProvider); } if (numberOfTimesSet > 1) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Only 1 overload for setInitialEventPositionProvider can be set. The overload is set " + numberOfTimesSet + " times.")); } return new EventProcessorClient(eventHubClientBuilder, getPartitionProcessorSupplier(), checkpointStore, processError, eventHubClientBuilder.createTracer(), processorOptions); }
"Only 1 overload for setInitialEventPositionProvider can be set. The overload is set "
public EventProcessorClient buildEventProcessorClient() { Objects.requireNonNull(processError, "'processError' cannot be null"); Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); if (processEvent == null && processEventBatch == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Either processEvent or processEventBatch " + "has to be set")); } if (processEvent != null && processEventBatch != null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Both processEvent and processEventBatch " + "cannot be set")); } if (loadBalancingUpdateInterval == null) { loadBalancingUpdateInterval = DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL; } if (partitionOwnershipExpirationInterval == null) { partitionOwnershipExpirationInterval = DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL; } final EventProcessorClientOptions processorOptions = new EventProcessorClientOptions() .setConsumerGroup(consumerGroup) .setBatchReceiveMode(processEventBatch != null) .setConsumerGroup(consumerGroup) .setLoadBalancingStrategy(loadBalancingStrategy) .setLoadBalancerUpdateInterval(loadBalancingUpdateInterval) .setMaxBatchSize(maxBatchSize) .setMaxWaitTime(maxWaitTime) .setPartitionOwnershipExpirationInterval(partitionOwnershipExpirationInterval) .setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties); int numberOfTimesSet = 0; if (initialPartitionEventPosition != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider( partitionId -> initialPartitionEventPosition.get(partitionId)); } if (initialEventPositionProvider != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider(initialEventPositionProvider); } if (numberOfTimesSet > 1) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Only 1 overload for initialEventPositionProvider can be set. The overload is set " + numberOfTimesSet + " times.")); } return new EventProcessorClient(eventHubClientBuilder, getPartitionProcessorSupplier(), checkpointStore, processError, eventHubClientBuilder.createTracer(), processorOptions); }
class EventProcessorClientBuilder implements TokenCredentialTrait<EventProcessorClientBuilder>, AzureNamedKeyCredentialTrait<EventProcessorClientBuilder>, ConnectionStringTrait<EventProcessorClientBuilder>, AzureSasCredentialTrait<EventProcessorClientBuilder>, AmqpTrait<EventProcessorClientBuilder>, ConfigurationTrait<EventProcessorClientBuilder> { /** * Default load balancing update interval. Balancing interval should account for latency between the client and the * storage account. */ public static final Duration DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL = Duration.ofSeconds(30); /** * Default ownership expiration. */ public static final Duration DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL = Duration.ofMinutes(2); private static final ClientLogger LOGGER = new ClientLogger(EventProcessorClientBuilder.class); private final EventHubClientBuilder eventHubClientBuilder; private String consumerGroup; private CheckpointStore checkpointStore; private Consumer<EventContext> processEvent; private Consumer<EventBatchContext> processEventBatch; private Consumer<ErrorContext> processError; private Consumer<InitializationContext> processPartitionInitialization; private Consumer<CloseContext> processPartitionClose; private boolean trackLastEnqueuedEventProperties; private Map<String, EventPosition> initialPartitionEventPosition = null; private int maxBatchSize = 1; private Duration maxWaitTime; private Duration loadBalancingUpdateInterval; private Duration partitionOwnershipExpirationInterval; private LoadBalancingStrategy loadBalancingStrategy = LoadBalancingStrategy.GREEDY; private EventPosition defaultInitialEventPosition = null; private Function<String, EventPosition> initialEventPositionProvider; /** * Creates a new instance of {@link EventProcessorClientBuilder}. */ public EventProcessorClientBuilder() { eventHubClientBuilder = new EventHubClientBuilder(); } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventProcessorClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { eventHubClientBuilder.fullyQualifiedNamespace(fullyQualifiedNamespace); return this; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventProcessorClientBuilder eventHubName(String eventHubName) { eventHubClientBuilder.eventHubName(eventHubName); return this; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding * {@literal "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, * "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} is {@code null}. * @throws IllegalArgumentException if {@code connectionString} is empty. Or, the {@code connectionString} does * not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventProcessorClientBuilder connectionString(String connectionString) { eventHubClientBuilder.connectionString(connectionString); return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventProcessorClientBuilder connectionString(String connectionString, String eventHubName) { eventHubClientBuilder.connectionString(connectionString, eventHubName); return this; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder configuration(Configuration configuration) { eventHubClientBuilder.configuration(configuration); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credential} is null. */ @Override public EventProcessorClientBuilder credential(TokenCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureSasCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through an * intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventProcessorClientBuilder customEndpointAddress(String customEndpointAddress) { eventHubClientBuilder.customEndpointAddress(customEndpointAddress); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, * {@link AmqpTransportType * * @param proxyOptions The proxy options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder proxyOptions(ProxyOptions proxyOptions) { eventHubClientBuilder.proxyOptions(proxyOptions); return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is * {@link AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder transportType(AmqpTransportType transport) { eventHubClientBuilder.transportType(transport); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventProcessorClientBuilder} object. * * @deprecated Replaced by {@link */ @Deprecated public EventProcessorClientBuilder retry(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder retryOptions(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the client options for the processor client. The application id set on the client options will be used for * tracing. The headers set on {@code ClientOptions} are currently not used but can be used in later releases to add * to AMQP message. * * @param clientOptions The client options. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder clientOptions(ClientOptions clientOptions) { eventHubClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the consumer group name from which the {@link EventProcessorClient} should consume events. * * @param consumerGroup The consumer group name this {@link EventProcessorClient} should consume events. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code consumerGroup} is {@code null}. */ public EventProcessorClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); return this; } /** * Sets the {@link CheckpointStore} the {@link EventProcessorClient} will use for storing partition ownership and * checkpoint information. * * <p> * Users can, optionally, provide their own implementation of {@link CheckpointStore} which will store ownership and * checkpoint information. * </p> * * @param checkpointStore Implementation of {@link CheckpointStore}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code checkpointStore} is {@code null}. */ public EventProcessorClientBuilder checkpointStore(CheckpointStore checkpointStore) { this.checkpointStore = Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); return this; } /** * The time interval between load balancing update cycles. This is also generally the interval at which ownership of * partitions are renewed. By default, this interval is set to 10 seconds. * * @param loadBalancingUpdateInterval The time duration between load balancing update cycles. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingUpdateInterval} is {@code null}. * @throws IllegalArgumentException if {@code loadBalancingUpdateInterval} is zero or a negative duration. */ public EventProcessorClientBuilder loadBalancingUpdateInterval(Duration loadBalancingUpdateInterval) { Objects.requireNonNull(loadBalancingUpdateInterval, "'loadBalancingUpdateInterval' cannot be null"); if (loadBalancingUpdateInterval.isZero() || loadBalancingUpdateInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'loadBalancingUpdateInterval' " + "should be a positive duration")); } this.loadBalancingUpdateInterval = loadBalancingUpdateInterval; return this; } /** * The time duration after which the ownership of partition expires if it's not renewed by the owning processor * instance. This is the duration that this processor instance will wait before taking over the ownership of * partitions previously owned by an inactive processor. By default, this duration is set to a minute. * * @param partitionOwnershipExpirationInterval The time duration after which the ownership of partition * expires. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code partitionOwnershipExpirationInterval} is {@code null}. * @throws IllegalArgumentException if {@code partitionOwnershipExpirationInterval} is zero or a negative * duration. */ public EventProcessorClientBuilder partitionOwnershipExpirationInterval( Duration partitionOwnershipExpirationInterval) { Objects.requireNonNull(partitionOwnershipExpirationInterval, "'partitionOwnershipExpirationInterval' cannot " + "be null"); if (partitionOwnershipExpirationInterval.isZero() || partitionOwnershipExpirationInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'partitionOwnershipExpirationInterval' " + "should be a positive duration")); } this.partitionOwnershipExpirationInterval = partitionOwnershipExpirationInterval; return this; } /** * The {@link LoadBalancingStrategy} the {@link EventProcessorClient event processor} will use for claiming * partition ownership. By default, a {@link LoadBalancingStrategy * * @param loadBalancingStrategy The {@link LoadBalancingStrategy} to use. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingStrategy} is {@code null}. */ public EventProcessorClientBuilder loadBalancingStrategy(LoadBalancingStrategy loadBalancingStrategy) { this.loadBalancingStrategy = Objects.requireNonNull(loadBalancingStrategy, "'loadBalancingStrategy' cannot be" + " null"); return this; } /** * Sets the count used by the receivers to control the number of events each consumer will actively receive and * queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The number of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * * @throws IllegalArgumentException if {@code prefetchCount} is less than 1 or greater than 8000. */ public EventProcessorClientBuilder prefetchCount(int prefetchCount) { eventHubClientBuilder.prefetchCount(prefetchCount); return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. * * @param processEvent The callback that's called when an event is received by this * {@link EventProcessorClient}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent) { return this.processEvent(processEvent, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEvent The callback that's called when an event is received by this {@link EventProcessorClient} * or when the max wait duration has expired. * @param maxWaitTime The max time duration to wait to receive an event before invoking this handler. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent, Duration maxWaitTime) { this.processEvent = Objects.requireNonNull(processEvent, "'processEvent' cannot be null"); if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEventBatch The callback that's called when an event is received by this * {@link EventProcessorClient} or when the max wait duration has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize) { return this.processEventBatch(processEventBatch, maxBatchSize, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * <!-- src_embed com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * <pre> * TokenCredential credential = new DefaultAzureCredentialBuilder& * * & * & * EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder& * .consumerGroup& * .checkpointStore& * .processEventBatch& * eventBatchContext.getEvents& * System.out.printf& * eventBatchContext.getPartitionContext& * eventData.getSequenceNumber& * & * & * .processError& * System.out.printf& * errorContext.getPartitionContext& * errorContext.getThrowable& * & * .buildEventProcessorClient& * </pre> * <!-- end com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * * @param processEventBatch The callback that's called when an event is received or when the max wait duration * has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * @param maxWaitTime The max time duration to wait to receive a batch of events upto the max batch size before * invoking this callback. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize, Duration maxWaitTime) { if (maxBatchSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxBatchSize' should be greater than 0")); } if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.processEventBatch = Objects.requireNonNull(processEventBatch, "'processEventBatch' cannot be null"); this.maxBatchSize = maxBatchSize; this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called when an error occurs while processing events. The input contains the partition * information where the error happened. * * @param processError The callback that's called when an error occurs while processing events. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processError(Consumer<ErrorContext> processError) { this.processError = processError; return this; } /** * The function that is called before processing starts for a partition. The input contains the partition * information along with a default starting position for processing events that will be used in the case of a * checkpoint unavailable in {@link CheckpointStore}. Users can update this position if a different starting * position is preferred. * * @param initializePartition The callback that's called before processing starts for a partition * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionInitialization( Consumer<InitializationContext> initializePartition) { this.processPartitionInitialization = initializePartition; return this; } /** * The function that is called when a processing for a partition stops. The input contains the partition information * along with the reason for stopping the event processing for this partition. * * @param closePartition The callback that's called after processing for a partition stops. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionClose(Consumer<CloseContext> closePartition) { this.processPartitionClose = closePartition; return this; } /** * Sets whether or not the event processor should request information on the last enqueued event on its associated * partition, and track that information as events are received. * * <p>When information about the partition's last enqueued event is being tracked, each event received from the * Event Hubs service will carry metadata about the partition that it otherwise would not. This results in a small * amount of additional network bandwidth consumption that is generally a favorable trade-off when considered * against periodically making requests for partition properties using the Event Hub client.</p> * * @param trackLastEnqueuedEventProperties {@code true} if the resulting events will keep track of the last * enqueued information for that partition; {@code false} otherwise. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder trackLastEnqueuedEventProperties(boolean trackLastEnqueuedEventProperties) { this.trackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties; return this; } /** * Sets the default starting position for each partition if a checkpoint for that partition does not exist in the * {@link CheckpointStore}. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialEventPosition Event position to start reading events. Applies to every partition in the Event Hub * without a checkpoint nor an entry in the {@link * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition(EventPosition initialEventPosition) { this.defaultInitialEventPosition = initialEventPosition; return this; } /** * Sets the map containing the event position to use for each partition if a checkpoint for the partition does not * exist in {@link CheckpointStore}. This map is keyed off of the partition id. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialPartitionEventPosition Map of initial event positions for partition ids. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition( Map<String, EventPosition> initialPartitionEventPosition) { this.initialPartitionEventPosition = Objects.requireNonNull(initialPartitionEventPosition, "'initialPartitionEventPosition' cannot be null."); return this; } /** * Sets the default starting position for each partition if a checkpoint for that partition does not exist in the * {@link CheckpointStore}. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialEventPositionProvider Function that maps the given {@code partitionId} to an * {@link EventPosition}. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition( Function<String, EventPosition> initialEventPositionProvider) { this.initialEventPositionProvider = initialEventPositionProvider; return this; } /** * This will create a new {@link EventProcessorClient} configured with the options set in this builder. Each call to * this method will return a new instance of {@link EventProcessorClient}. * * <p> * All partitions processed by this {@link EventProcessorClient} will start processing from * {@link EventPosition * </p> * * @return A new instance of {@link EventProcessorClient}. * * @throws NullPointerException if {@code processEvent} or {@code processError} or {@code checkpointStore} or * {@code consumerGroup} is {@code null}. * @throws IllegalArgumentException if the credentials have not been set using either * {@link * specified but the transport type is not {@link AmqpTransportType * than one overload for {@code setInitialEventPositionProvider} is set. */ private Supplier<PartitionProcessor> getPartitionProcessorSupplier() { return () -> new PartitionProcessor() { @Override public void processEvent(EventContext eventContext) { if (processEvent != null) { processEvent.accept(eventContext); } } @Override public void processEventBatch(EventBatchContext eventBatchContext) { if (processEventBatch != null) { processEventBatch.accept(eventBatchContext); } else { super.processEventBatch(eventBatchContext); } } @Override public void initialize(InitializationContext initializationContext) { if (processPartitionInitialization != null) { processPartitionInitialization.accept(initializationContext); } else { super.initialize(initializationContext); } } @Override public void processError(ErrorContext errorContext) { processError.accept(errorContext); } @Override public void close(CloseContext closeContext) { if (processPartitionClose != null) { processPartitionClose.accept(closeContext); } else { super.close(closeContext); } } }; } }
class EventProcessorClientBuilder implements TokenCredentialTrait<EventProcessorClientBuilder>, AzureNamedKeyCredentialTrait<EventProcessorClientBuilder>, ConnectionStringTrait<EventProcessorClientBuilder>, AzureSasCredentialTrait<EventProcessorClientBuilder>, AmqpTrait<EventProcessorClientBuilder>, ConfigurationTrait<EventProcessorClientBuilder> { /** * Default load balancing update interval. Balancing interval should account for latency between the client and the * storage account. */ public static final Duration DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL = Duration.ofSeconds(30); /** * Default ownership expiration. */ public static final Duration DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL = Duration.ofMinutes(2); private static final ClientLogger LOGGER = new ClientLogger(EventProcessorClientBuilder.class); private final EventHubClientBuilder eventHubClientBuilder; private String consumerGroup; private CheckpointStore checkpointStore; private Consumer<EventContext> processEvent; private Consumer<EventBatchContext> processEventBatch; private Consumer<ErrorContext> processError; private Consumer<InitializationContext> processPartitionInitialization; private Consumer<CloseContext> processPartitionClose; private boolean trackLastEnqueuedEventProperties; private Map<String, EventPosition> initialPartitionEventPosition = null; private int maxBatchSize = 1; private Duration maxWaitTime; private Duration loadBalancingUpdateInterval; private Duration partitionOwnershipExpirationInterval; private LoadBalancingStrategy loadBalancingStrategy = LoadBalancingStrategy.GREEDY; private Function<String, EventPosition> initialEventPositionProvider; /** * Creates a new instance of {@link EventProcessorClientBuilder}. */ public EventProcessorClientBuilder() { eventHubClientBuilder = new EventHubClientBuilder(); } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventProcessorClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { eventHubClientBuilder.fullyQualifiedNamespace(fullyQualifiedNamespace); return this; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventProcessorClientBuilder eventHubName(String eventHubName) { eventHubClientBuilder.eventHubName(eventHubName); return this; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding * {@literal "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, * "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} is {@code null}. * @throws IllegalArgumentException if {@code connectionString} is empty. Or, the {@code connectionString} does * not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventProcessorClientBuilder connectionString(String connectionString) { eventHubClientBuilder.connectionString(connectionString); return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventProcessorClientBuilder connectionString(String connectionString, String eventHubName) { eventHubClientBuilder.connectionString(connectionString, eventHubName); return this; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder configuration(Configuration configuration) { eventHubClientBuilder.configuration(configuration); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credential} is null. */ @Override public EventProcessorClientBuilder credential(TokenCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureSasCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through an * intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventProcessorClientBuilder customEndpointAddress(String customEndpointAddress) { eventHubClientBuilder.customEndpointAddress(customEndpointAddress); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, * {@link AmqpTransportType * * @param proxyOptions The proxy options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder proxyOptions(ProxyOptions proxyOptions) { eventHubClientBuilder.proxyOptions(proxyOptions); return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is * {@link AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder transportType(AmqpTransportType transport) { eventHubClientBuilder.transportType(transport); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventProcessorClientBuilder} object. * * @deprecated Replaced by {@link */ @Deprecated public EventProcessorClientBuilder retry(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder retryOptions(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the client options for the processor client. The application id set on the client options will be used for * tracing. The headers set on {@code ClientOptions} are currently not used but can be used in later releases to add * to AMQP message. * * @param clientOptions The client options. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder clientOptions(ClientOptions clientOptions) { eventHubClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the consumer group name from which the {@link EventProcessorClient} should consume events. * * @param consumerGroup The consumer group name this {@link EventProcessorClient} should consume events. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code consumerGroup} is {@code null}. */ public EventProcessorClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); return this; } /** * Sets the {@link CheckpointStore} the {@link EventProcessorClient} will use for storing partition ownership and * checkpoint information. * * <p> * Users can, optionally, provide their own implementation of {@link CheckpointStore} which will store ownership and * checkpoint information. * </p> * * @param checkpointStore Implementation of {@link CheckpointStore}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code checkpointStore} is {@code null}. */ public EventProcessorClientBuilder checkpointStore(CheckpointStore checkpointStore) { this.checkpointStore = Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); return this; } /** * The time interval between load balancing update cycles. This is also generally the interval at which ownership of * partitions are renewed. By default, this interval is set to 10 seconds. * * @param loadBalancingUpdateInterval The time duration between load balancing update cycles. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingUpdateInterval} is {@code null}. * @throws IllegalArgumentException if {@code loadBalancingUpdateInterval} is zero or a negative duration. */ public EventProcessorClientBuilder loadBalancingUpdateInterval(Duration loadBalancingUpdateInterval) { Objects.requireNonNull(loadBalancingUpdateInterval, "'loadBalancingUpdateInterval' cannot be null"); if (loadBalancingUpdateInterval.isZero() || loadBalancingUpdateInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'loadBalancingUpdateInterval' " + "should be a positive duration")); } this.loadBalancingUpdateInterval = loadBalancingUpdateInterval; return this; } /** * The time duration after which the ownership of partition expires if it's not renewed by the owning processor * instance. This is the duration that this processor instance will wait before taking over the ownership of * partitions previously owned by an inactive processor. By default, this duration is set to a minute. * * @param partitionOwnershipExpirationInterval The time duration after which the ownership of partition * expires. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code partitionOwnershipExpirationInterval} is {@code null}. * @throws IllegalArgumentException if {@code partitionOwnershipExpirationInterval} is zero or a negative * duration. */ public EventProcessorClientBuilder partitionOwnershipExpirationInterval( Duration partitionOwnershipExpirationInterval) { Objects.requireNonNull(partitionOwnershipExpirationInterval, "'partitionOwnershipExpirationInterval' cannot " + "be null"); if (partitionOwnershipExpirationInterval.isZero() || partitionOwnershipExpirationInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'partitionOwnershipExpirationInterval' " + "should be a positive duration")); } this.partitionOwnershipExpirationInterval = partitionOwnershipExpirationInterval; return this; } /** * The {@link LoadBalancingStrategy} the {@link EventProcessorClient event processor} will use for claiming * partition ownership. By default, a {@link LoadBalancingStrategy * * @param loadBalancingStrategy The {@link LoadBalancingStrategy} to use. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingStrategy} is {@code null}. */ public EventProcessorClientBuilder loadBalancingStrategy(LoadBalancingStrategy loadBalancingStrategy) { this.loadBalancingStrategy = Objects.requireNonNull(loadBalancingStrategy, "'loadBalancingStrategy' cannot be" + " null"); return this; } /** * Sets the count used by the receivers to control the number of events each consumer will actively receive and * queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The number of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * * @throws IllegalArgumentException if {@code prefetchCount} is less than 1 or greater than 8000. */ public EventProcessorClientBuilder prefetchCount(int prefetchCount) { eventHubClientBuilder.prefetchCount(prefetchCount); return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. * * @param processEvent The callback that's called when an event is received by this * {@link EventProcessorClient}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent) { return this.processEvent(processEvent, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEvent The callback that's called when an event is received by this {@link EventProcessorClient} * or when the max wait duration has expired. * @param maxWaitTime The max time duration to wait to receive an event before invoking this handler. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent, Duration maxWaitTime) { this.processEvent = Objects.requireNonNull(processEvent, "'processEvent' cannot be null"); if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEventBatch The callback that's called when an event is received by this * {@link EventProcessorClient} or when the max wait duration has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize) { return this.processEventBatch(processEventBatch, maxBatchSize, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * <!-- src_embed com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * <pre> * TokenCredential credential = new DefaultAzureCredentialBuilder& * * & * & * EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder& * .consumerGroup& * .checkpointStore& * .processEventBatch& * eventBatchContext.getEvents& * System.out.printf& * eventBatchContext.getPartitionContext& * eventData.getSequenceNumber& * & * & * .processError& * System.out.printf& * errorContext.getPartitionContext& * errorContext.getThrowable& * & * .buildEventProcessorClient& * </pre> * <!-- end com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * * @param processEventBatch The callback that's called when an event is received or when the max wait duration * has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * @param maxWaitTime The max time duration to wait to receive a batch of events upto the max batch size before * invoking this callback. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize, Duration maxWaitTime) { if (maxBatchSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxBatchSize' should be greater than 0")); } if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.processEventBatch = Objects.requireNonNull(processEventBatch, "'processEventBatch' cannot be null"); this.maxBatchSize = maxBatchSize; this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called when an error occurs while processing events. The input contains the partition * information where the error happened. * * @param processError The callback that's called when an error occurs while processing events. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processError(Consumer<ErrorContext> processError) { this.processError = processError; return this; } /** * The function that is called before processing starts for a partition. The input contains the partition * information along with a default starting position for processing events that will be used in the case of a * checkpoint unavailable in {@link CheckpointStore}. Users can update this position if a different starting * position is preferred. * * @param initializePartition The callback that's called before processing starts for a partition * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionInitialization( Consumer<InitializationContext> initializePartition) { this.processPartitionInitialization = initializePartition; return this; } /** * The function that is called when a processing for a partition stops. The input contains the partition information * along with the reason for stopping the event processing for this partition. * * @param closePartition The callback that's called after processing for a partition stops. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionClose(Consumer<CloseContext> closePartition) { this.processPartitionClose = closePartition; return this; } /** * Sets whether or not the event processor should request information on the last enqueued event on its associated * partition, and track that information as events are received. * * <p>When information about the partition's last enqueued event is being tracked, each event received from the * Event Hubs service will carry metadata about the partition that it otherwise would not. This results in a small * amount of additional network bandwidth consumption that is generally a favorable trade-off when considered * against periodically making requests for partition properties using the Event Hub client.</p> * * @param trackLastEnqueuedEventProperties {@code true} if the resulting events will keep track of the last * enqueued information for that partition; {@code false} otherwise. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder trackLastEnqueuedEventProperties(boolean trackLastEnqueuedEventProperties) { this.trackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties; return this; } /** * Sets the map containing the event position to use for each partition if a checkpoint for the partition does not * exist in {@link CheckpointStore}. This map is keyed off of the partition id. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialPartitionEventPosition Map of initial event positions for partition ids. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition( Map<String, EventPosition> initialPartitionEventPosition) { this.initialPartitionEventPosition = Objects.requireNonNull(initialPartitionEventPosition, "'initialPartitionEventPosition' cannot be null."); return this; } /** * Sets the default starting position for each partition if a checkpoint for that partition does not exist in the * {@link CheckpointStore}. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialEventPositionProvider Function that maps the given {@code partitionId} to an * {@link EventPosition}. * * @return The updated {@link EventProcessorClientBuilder} instance. * @throws NullPointerException if {@code initialEventPositionProvider} is null. */ public EventProcessorClientBuilder initialPartitionEventPosition( Function<String, EventPosition> initialEventPositionProvider) { this.initialEventPositionProvider = Objects.requireNonNull(initialEventPositionProvider, "'initialEventPositionProvider' cannot be null."); return this; } /** * This will create a new {@link EventProcessorClient} configured with the options set in this builder. Each call to * this method will return a new instance of {@link EventProcessorClient}. * * <p> * All partitions processed by this {@link EventProcessorClient} will start processing from * {@link EventPosition * </p> * * @return A new instance of {@link EventProcessorClient}. * * @throws NullPointerException if {@code processEvent} or {@code processError} or {@code checkpointStore} or * {@code consumerGroup} is {@code null}. * @throws IllegalArgumentException if the credentials have not been set using either * {@link * specified but the transport type is not {@link AmqpTransportType * than one overload for {@code setInitialEventPositionProvider} is set. */ private Supplier<PartitionProcessor> getPartitionProcessorSupplier() { return () -> new PartitionProcessor() { @Override public void processEvent(EventContext eventContext) { if (processEvent != null) { processEvent.accept(eventContext); } } @Override public void processEventBatch(EventBatchContext eventBatchContext) { if (processEventBatch != null) { processEventBatch.accept(eventBatchContext); } else { super.processEventBatch(eventBatchContext); } } @Override public void initialize(InitializationContext initializationContext) { if (processPartitionInitialization != null) { processPartitionInitialization.accept(initializationContext); } else { super.initialize(initializationContext); } } @Override public void processError(ErrorContext errorContext) { processError.accept(errorContext); } @Override public void close(CloseContext closeContext) { if (processPartitionClose != null) { processPartitionClose.accept(closeContext); } else { super.close(closeContext); } } }; } }
THanks. I will fix that.
public EventProcessorClient buildEventProcessorClient() { Objects.requireNonNull(processError, "'processError' cannot be null"); Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); if (processEvent == null && processEventBatch == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Either processEvent or processEventBatch " + "has to be set")); } if (processEvent != null && processEventBatch != null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Both processEvent and processEventBatch " + "cannot be set")); } if (loadBalancingUpdateInterval == null) { loadBalancingUpdateInterval = DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL; } if (partitionOwnershipExpirationInterval == null) { partitionOwnershipExpirationInterval = DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL; } final EventProcessorClientOptions processorOptions = new EventProcessorClientOptions() .setConsumerGroup(consumerGroup) .setBatchReceiveMode(processEventBatch != null) .setConsumerGroup(consumerGroup) .setLoadBalancingStrategy(loadBalancingStrategy) .setLoadBalancerUpdateInterval(loadBalancingUpdateInterval) .setMaxBatchSize(maxBatchSize) .setMaxWaitTime(maxWaitTime) .setPartitionOwnershipExpirationInterval(partitionOwnershipExpirationInterval) .setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties); int numberOfTimesSet = 0; if (defaultInitialEventPosition != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider(unused -> defaultInitialEventPosition); } if (initialPartitionEventPosition != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider( partitionId -> initialPartitionEventPosition.get(partitionId)); } if (initialEventPositionProvider != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider(initialEventPositionProvider); } if (numberOfTimesSet > 1) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Only 1 overload for setInitialEventPositionProvider can be set. The overload is set " + numberOfTimesSet + " times.")); } return new EventProcessorClient(eventHubClientBuilder, getPartitionProcessorSupplier(), checkpointStore, processError, eventHubClientBuilder.createTracer(), processorOptions); }
"Only 1 overload for setInitialEventPositionProvider can be set. The overload is set "
public EventProcessorClient buildEventProcessorClient() { Objects.requireNonNull(processError, "'processError' cannot be null"); Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); if (processEvent == null && processEventBatch == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Either processEvent or processEventBatch " + "has to be set")); } if (processEvent != null && processEventBatch != null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Both processEvent and processEventBatch " + "cannot be set")); } if (loadBalancingUpdateInterval == null) { loadBalancingUpdateInterval = DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL; } if (partitionOwnershipExpirationInterval == null) { partitionOwnershipExpirationInterval = DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL; } final EventProcessorClientOptions processorOptions = new EventProcessorClientOptions() .setConsumerGroup(consumerGroup) .setBatchReceiveMode(processEventBatch != null) .setConsumerGroup(consumerGroup) .setLoadBalancingStrategy(loadBalancingStrategy) .setLoadBalancerUpdateInterval(loadBalancingUpdateInterval) .setMaxBatchSize(maxBatchSize) .setMaxWaitTime(maxWaitTime) .setPartitionOwnershipExpirationInterval(partitionOwnershipExpirationInterval) .setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties); int numberOfTimesSet = 0; if (initialPartitionEventPosition != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider( partitionId -> initialPartitionEventPosition.get(partitionId)); } if (initialEventPositionProvider != null) { numberOfTimesSet++; processorOptions.setInitialEventPositionProvider(initialEventPositionProvider); } if (numberOfTimesSet > 1) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Only 1 overload for initialEventPositionProvider can be set. The overload is set " + numberOfTimesSet + " times.")); } return new EventProcessorClient(eventHubClientBuilder, getPartitionProcessorSupplier(), checkpointStore, processError, eventHubClientBuilder.createTracer(), processorOptions); }
class EventProcessorClientBuilder implements TokenCredentialTrait<EventProcessorClientBuilder>, AzureNamedKeyCredentialTrait<EventProcessorClientBuilder>, ConnectionStringTrait<EventProcessorClientBuilder>, AzureSasCredentialTrait<EventProcessorClientBuilder>, AmqpTrait<EventProcessorClientBuilder>, ConfigurationTrait<EventProcessorClientBuilder> { /** * Default load balancing update interval. Balancing interval should account for latency between the client and the * storage account. */ public static final Duration DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL = Duration.ofSeconds(30); /** * Default ownership expiration. */ public static final Duration DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL = Duration.ofMinutes(2); private static final ClientLogger LOGGER = new ClientLogger(EventProcessorClientBuilder.class); private final EventHubClientBuilder eventHubClientBuilder; private String consumerGroup; private CheckpointStore checkpointStore; private Consumer<EventContext> processEvent; private Consumer<EventBatchContext> processEventBatch; private Consumer<ErrorContext> processError; private Consumer<InitializationContext> processPartitionInitialization; private Consumer<CloseContext> processPartitionClose; private boolean trackLastEnqueuedEventProperties; private Map<String, EventPosition> initialPartitionEventPosition = null; private int maxBatchSize = 1; private Duration maxWaitTime; private Duration loadBalancingUpdateInterval; private Duration partitionOwnershipExpirationInterval; private LoadBalancingStrategy loadBalancingStrategy = LoadBalancingStrategy.GREEDY; private EventPosition defaultInitialEventPosition = null; private Function<String, EventPosition> initialEventPositionProvider; /** * Creates a new instance of {@link EventProcessorClientBuilder}. */ public EventProcessorClientBuilder() { eventHubClientBuilder = new EventHubClientBuilder(); } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventProcessorClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { eventHubClientBuilder.fullyQualifiedNamespace(fullyQualifiedNamespace); return this; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventProcessorClientBuilder eventHubName(String eventHubName) { eventHubClientBuilder.eventHubName(eventHubName); return this; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding * {@literal "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, * "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} is {@code null}. * @throws IllegalArgumentException if {@code connectionString} is empty. Or, the {@code connectionString} does * not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventProcessorClientBuilder connectionString(String connectionString) { eventHubClientBuilder.connectionString(connectionString); return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventProcessorClientBuilder connectionString(String connectionString, String eventHubName) { eventHubClientBuilder.connectionString(connectionString, eventHubName); return this; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder configuration(Configuration configuration) { eventHubClientBuilder.configuration(configuration); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credential} is null. */ @Override public EventProcessorClientBuilder credential(TokenCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureSasCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through an * intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventProcessorClientBuilder customEndpointAddress(String customEndpointAddress) { eventHubClientBuilder.customEndpointAddress(customEndpointAddress); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, * {@link AmqpTransportType * * @param proxyOptions The proxy options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder proxyOptions(ProxyOptions proxyOptions) { eventHubClientBuilder.proxyOptions(proxyOptions); return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is * {@link AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder transportType(AmqpTransportType transport) { eventHubClientBuilder.transportType(transport); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventProcessorClientBuilder} object. * * @deprecated Replaced by {@link */ @Deprecated public EventProcessorClientBuilder retry(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder retryOptions(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the client options for the processor client. The application id set on the client options will be used for * tracing. The headers set on {@code ClientOptions} are currently not used but can be used in later releases to add * to AMQP message. * * @param clientOptions The client options. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder clientOptions(ClientOptions clientOptions) { eventHubClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the consumer group name from which the {@link EventProcessorClient} should consume events. * * @param consumerGroup The consumer group name this {@link EventProcessorClient} should consume events. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code consumerGroup} is {@code null}. */ public EventProcessorClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); return this; } /** * Sets the {@link CheckpointStore} the {@link EventProcessorClient} will use for storing partition ownership and * checkpoint information. * * <p> * Users can, optionally, provide their own implementation of {@link CheckpointStore} which will store ownership and * checkpoint information. * </p> * * @param checkpointStore Implementation of {@link CheckpointStore}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code checkpointStore} is {@code null}. */ public EventProcessorClientBuilder checkpointStore(CheckpointStore checkpointStore) { this.checkpointStore = Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); return this; } /** * The time interval between load balancing update cycles. This is also generally the interval at which ownership of * partitions are renewed. By default, this interval is set to 10 seconds. * * @param loadBalancingUpdateInterval The time duration between load balancing update cycles. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingUpdateInterval} is {@code null}. * @throws IllegalArgumentException if {@code loadBalancingUpdateInterval} is zero or a negative duration. */ public EventProcessorClientBuilder loadBalancingUpdateInterval(Duration loadBalancingUpdateInterval) { Objects.requireNonNull(loadBalancingUpdateInterval, "'loadBalancingUpdateInterval' cannot be null"); if (loadBalancingUpdateInterval.isZero() || loadBalancingUpdateInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'loadBalancingUpdateInterval' " + "should be a positive duration")); } this.loadBalancingUpdateInterval = loadBalancingUpdateInterval; return this; } /** * The time duration after which the ownership of partition expires if it's not renewed by the owning processor * instance. This is the duration that this processor instance will wait before taking over the ownership of * partitions previously owned by an inactive processor. By default, this duration is set to a minute. * * @param partitionOwnershipExpirationInterval The time duration after which the ownership of partition * expires. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code partitionOwnershipExpirationInterval} is {@code null}. * @throws IllegalArgumentException if {@code partitionOwnershipExpirationInterval} is zero or a negative * duration. */ public EventProcessorClientBuilder partitionOwnershipExpirationInterval( Duration partitionOwnershipExpirationInterval) { Objects.requireNonNull(partitionOwnershipExpirationInterval, "'partitionOwnershipExpirationInterval' cannot " + "be null"); if (partitionOwnershipExpirationInterval.isZero() || partitionOwnershipExpirationInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'partitionOwnershipExpirationInterval' " + "should be a positive duration")); } this.partitionOwnershipExpirationInterval = partitionOwnershipExpirationInterval; return this; } /** * The {@link LoadBalancingStrategy} the {@link EventProcessorClient event processor} will use for claiming * partition ownership. By default, a {@link LoadBalancingStrategy * * @param loadBalancingStrategy The {@link LoadBalancingStrategy} to use. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingStrategy} is {@code null}. */ public EventProcessorClientBuilder loadBalancingStrategy(LoadBalancingStrategy loadBalancingStrategy) { this.loadBalancingStrategy = Objects.requireNonNull(loadBalancingStrategy, "'loadBalancingStrategy' cannot be" + " null"); return this; } /** * Sets the count used by the receivers to control the number of events each consumer will actively receive and * queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The number of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * * @throws IllegalArgumentException if {@code prefetchCount} is less than 1 or greater than 8000. */ public EventProcessorClientBuilder prefetchCount(int prefetchCount) { eventHubClientBuilder.prefetchCount(prefetchCount); return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. * * @param processEvent The callback that's called when an event is received by this * {@link EventProcessorClient}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent) { return this.processEvent(processEvent, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEvent The callback that's called when an event is received by this {@link EventProcessorClient} * or when the max wait duration has expired. * @param maxWaitTime The max time duration to wait to receive an event before invoking this handler. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent, Duration maxWaitTime) { this.processEvent = Objects.requireNonNull(processEvent, "'processEvent' cannot be null"); if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEventBatch The callback that's called when an event is received by this * {@link EventProcessorClient} or when the max wait duration has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize) { return this.processEventBatch(processEventBatch, maxBatchSize, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * <!-- src_embed com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * <pre> * TokenCredential credential = new DefaultAzureCredentialBuilder& * * & * & * EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder& * .consumerGroup& * .checkpointStore& * .processEventBatch& * eventBatchContext.getEvents& * System.out.printf& * eventBatchContext.getPartitionContext& * eventData.getSequenceNumber& * & * & * .processError& * System.out.printf& * errorContext.getPartitionContext& * errorContext.getThrowable& * & * .buildEventProcessorClient& * </pre> * <!-- end com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * * @param processEventBatch The callback that's called when an event is received or when the max wait duration * has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * @param maxWaitTime The max time duration to wait to receive a batch of events upto the max batch size before * invoking this callback. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize, Duration maxWaitTime) { if (maxBatchSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxBatchSize' should be greater than 0")); } if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.processEventBatch = Objects.requireNonNull(processEventBatch, "'processEventBatch' cannot be null"); this.maxBatchSize = maxBatchSize; this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called when an error occurs while processing events. The input contains the partition * information where the error happened. * * @param processError The callback that's called when an error occurs while processing events. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processError(Consumer<ErrorContext> processError) { this.processError = processError; return this; } /** * The function that is called before processing starts for a partition. The input contains the partition * information along with a default starting position for processing events that will be used in the case of a * checkpoint unavailable in {@link CheckpointStore}. Users can update this position if a different starting * position is preferred. * * @param initializePartition The callback that's called before processing starts for a partition * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionInitialization( Consumer<InitializationContext> initializePartition) { this.processPartitionInitialization = initializePartition; return this; } /** * The function that is called when a processing for a partition stops. The input contains the partition information * along with the reason for stopping the event processing for this partition. * * @param closePartition The callback that's called after processing for a partition stops. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionClose(Consumer<CloseContext> closePartition) { this.processPartitionClose = closePartition; return this; } /** * Sets whether or not the event processor should request information on the last enqueued event on its associated * partition, and track that information as events are received. * * <p>When information about the partition's last enqueued event is being tracked, each event received from the * Event Hubs service will carry metadata about the partition that it otherwise would not. This results in a small * amount of additional network bandwidth consumption that is generally a favorable trade-off when considered * against periodically making requests for partition properties using the Event Hub client.</p> * * @param trackLastEnqueuedEventProperties {@code true} if the resulting events will keep track of the last * enqueued information for that partition; {@code false} otherwise. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder trackLastEnqueuedEventProperties(boolean trackLastEnqueuedEventProperties) { this.trackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties; return this; } /** * Sets the default starting position for each partition if a checkpoint for that partition does not exist in the * {@link CheckpointStore}. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialEventPosition Event position to start reading events. Applies to every partition in the Event Hub * without a checkpoint nor an entry in the {@link * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition(EventPosition initialEventPosition) { this.defaultInitialEventPosition = initialEventPosition; return this; } /** * Sets the map containing the event position to use for each partition if a checkpoint for the partition does not * exist in {@link CheckpointStore}. This map is keyed off of the partition id. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialPartitionEventPosition Map of initial event positions for partition ids. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition( Map<String, EventPosition> initialPartitionEventPosition) { this.initialPartitionEventPosition = Objects.requireNonNull(initialPartitionEventPosition, "'initialPartitionEventPosition' cannot be null."); return this; } /** * Sets the default starting position for each partition if a checkpoint for that partition does not exist in the * {@link CheckpointStore}. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialEventPositionProvider Function that maps the given {@code partitionId} to an * {@link EventPosition}. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition( Function<String, EventPosition> initialEventPositionProvider) { this.initialEventPositionProvider = initialEventPositionProvider; return this; } /** * This will create a new {@link EventProcessorClient} configured with the options set in this builder. Each call to * this method will return a new instance of {@link EventProcessorClient}. * * <p> * All partitions processed by this {@link EventProcessorClient} will start processing from * {@link EventPosition * </p> * * @return A new instance of {@link EventProcessorClient}. * * @throws NullPointerException if {@code processEvent} or {@code processError} or {@code checkpointStore} or * {@code consumerGroup} is {@code null}. * @throws IllegalArgumentException if the credentials have not been set using either * {@link * specified but the transport type is not {@link AmqpTransportType * than one overload for {@code setInitialEventPositionProvider} is set. */ private Supplier<PartitionProcessor> getPartitionProcessorSupplier() { return () -> new PartitionProcessor() { @Override public void processEvent(EventContext eventContext) { if (processEvent != null) { processEvent.accept(eventContext); } } @Override public void processEventBatch(EventBatchContext eventBatchContext) { if (processEventBatch != null) { processEventBatch.accept(eventBatchContext); } else { super.processEventBatch(eventBatchContext); } } @Override public void initialize(InitializationContext initializationContext) { if (processPartitionInitialization != null) { processPartitionInitialization.accept(initializationContext); } else { super.initialize(initializationContext); } } @Override public void processError(ErrorContext errorContext) { processError.accept(errorContext); } @Override public void close(CloseContext closeContext) { if (processPartitionClose != null) { processPartitionClose.accept(closeContext); } else { super.close(closeContext); } } }; } }
class EventProcessorClientBuilder implements TokenCredentialTrait<EventProcessorClientBuilder>, AzureNamedKeyCredentialTrait<EventProcessorClientBuilder>, ConnectionStringTrait<EventProcessorClientBuilder>, AzureSasCredentialTrait<EventProcessorClientBuilder>, AmqpTrait<EventProcessorClientBuilder>, ConfigurationTrait<EventProcessorClientBuilder> { /** * Default load balancing update interval. Balancing interval should account for latency between the client and the * storage account. */ public static final Duration DEFAULT_LOAD_BALANCING_UPDATE_INTERVAL = Duration.ofSeconds(30); /** * Default ownership expiration. */ public static final Duration DEFAULT_OWNERSHIP_EXPIRATION_INTERVAL = Duration.ofMinutes(2); private static final ClientLogger LOGGER = new ClientLogger(EventProcessorClientBuilder.class); private final EventHubClientBuilder eventHubClientBuilder; private String consumerGroup; private CheckpointStore checkpointStore; private Consumer<EventContext> processEvent; private Consumer<EventBatchContext> processEventBatch; private Consumer<ErrorContext> processError; private Consumer<InitializationContext> processPartitionInitialization; private Consumer<CloseContext> processPartitionClose; private boolean trackLastEnqueuedEventProperties; private Map<String, EventPosition> initialPartitionEventPosition = null; private int maxBatchSize = 1; private Duration maxWaitTime; private Duration loadBalancingUpdateInterval; private Duration partitionOwnershipExpirationInterval; private LoadBalancingStrategy loadBalancingStrategy = LoadBalancingStrategy.GREEDY; private Function<String, EventPosition> initialEventPositionProvider; /** * Creates a new instance of {@link EventProcessorClientBuilder}. */ public EventProcessorClientBuilder() { eventHubClientBuilder = new EventHubClientBuilder(); } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventProcessorClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { eventHubClientBuilder.fullyQualifiedNamespace(fullyQualifiedNamespace); return this; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventProcessorClientBuilder eventHubName(String eventHubName) { eventHubClientBuilder.eventHubName(eventHubName); return this; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding * {@literal "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, * "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} is {@code null}. * @throws IllegalArgumentException if {@code connectionString} is empty. Or, the {@code connectionString} does * not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventProcessorClientBuilder connectionString(String connectionString) { eventHubClientBuilder.connectionString(connectionString); return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventProcessorClientBuilder connectionString(String connectionString, String eventHubName) { eventHubClientBuilder.connectionString(connectionString, eventHubName); return this; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder configuration(Configuration configuration) { eventHubClientBuilder.configuration(configuration); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credential} is null. */ @Override public EventProcessorClientBuilder credential(TokenCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureNamedKeyCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventProcessorClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { eventHubClientBuilder.credential(fullyQualifiedNamespace, eventHubName, credential); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. Access controls may be * specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws NullPointerException if {@code credentials} is null. */ @Override public EventProcessorClientBuilder credential(AzureSasCredential credential) { eventHubClientBuilder.credential(credential); return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through an * intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * * @return The updated {@link EventProcessorClientBuilder} object. * * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventProcessorClientBuilder customEndpointAddress(String customEndpointAddress) { eventHubClientBuilder.customEndpointAddress(customEndpointAddress); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, * {@link AmqpTransportType * * @param proxyOptions The proxy options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder proxyOptions(ProxyOptions proxyOptions) { eventHubClientBuilder.proxyOptions(proxyOptions); return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is * {@link AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder transportType(AmqpTransportType transport) { eventHubClientBuilder.transportType(transport); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventProcessorClientBuilder} object. * * @deprecated Replaced by {@link */ @Deprecated public EventProcessorClientBuilder retry(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder retryOptions(AmqpRetryOptions retryOptions) { eventHubClientBuilder.retryOptions(retryOptions); return this; } /** * Sets the client options for the processor client. The application id set on the client options will be used for * tracing. The headers set on {@code ClientOptions} are currently not used but can be used in later releases to add * to AMQP message. * * @param clientOptions The client options. * * @return The updated {@link EventProcessorClientBuilder} object. */ @Override public EventProcessorClientBuilder clientOptions(ClientOptions clientOptions) { eventHubClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the consumer group name from which the {@link EventProcessorClient} should consume events. * * @param consumerGroup The consumer group name this {@link EventProcessorClient} should consume events. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code consumerGroup} is {@code null}. */ public EventProcessorClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = Objects.requireNonNull(consumerGroup, "'consumerGroup' cannot be null"); return this; } /** * Sets the {@link CheckpointStore} the {@link EventProcessorClient} will use for storing partition ownership and * checkpoint information. * * <p> * Users can, optionally, provide their own implementation of {@link CheckpointStore} which will store ownership and * checkpoint information. * </p> * * @param checkpointStore Implementation of {@link CheckpointStore}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code checkpointStore} is {@code null}. */ public EventProcessorClientBuilder checkpointStore(CheckpointStore checkpointStore) { this.checkpointStore = Objects.requireNonNull(checkpointStore, "'checkpointStore' cannot be null"); return this; } /** * The time interval between load balancing update cycles. This is also generally the interval at which ownership of * partitions are renewed. By default, this interval is set to 10 seconds. * * @param loadBalancingUpdateInterval The time duration between load balancing update cycles. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingUpdateInterval} is {@code null}. * @throws IllegalArgumentException if {@code loadBalancingUpdateInterval} is zero or a negative duration. */ public EventProcessorClientBuilder loadBalancingUpdateInterval(Duration loadBalancingUpdateInterval) { Objects.requireNonNull(loadBalancingUpdateInterval, "'loadBalancingUpdateInterval' cannot be null"); if (loadBalancingUpdateInterval.isZero() || loadBalancingUpdateInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'loadBalancingUpdateInterval' " + "should be a positive duration")); } this.loadBalancingUpdateInterval = loadBalancingUpdateInterval; return this; } /** * The time duration after which the ownership of partition expires if it's not renewed by the owning processor * instance. This is the duration that this processor instance will wait before taking over the ownership of * partitions previously owned by an inactive processor. By default, this duration is set to a minute. * * @param partitionOwnershipExpirationInterval The time duration after which the ownership of partition * expires. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code partitionOwnershipExpirationInterval} is {@code null}. * @throws IllegalArgumentException if {@code partitionOwnershipExpirationInterval} is zero or a negative * duration. */ public EventProcessorClientBuilder partitionOwnershipExpirationInterval( Duration partitionOwnershipExpirationInterval) { Objects.requireNonNull(partitionOwnershipExpirationInterval, "'partitionOwnershipExpirationInterval' cannot " + "be null"); if (partitionOwnershipExpirationInterval.isZero() || partitionOwnershipExpirationInterval.isNegative()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'partitionOwnershipExpirationInterval' " + "should be a positive duration")); } this.partitionOwnershipExpirationInterval = partitionOwnershipExpirationInterval; return this; } /** * The {@link LoadBalancingStrategy} the {@link EventProcessorClient event processor} will use for claiming * partition ownership. By default, a {@link LoadBalancingStrategy * * @param loadBalancingStrategy The {@link LoadBalancingStrategy} to use. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code loadBalancingStrategy} is {@code null}. */ public EventProcessorClientBuilder loadBalancingStrategy(LoadBalancingStrategy loadBalancingStrategy) { this.loadBalancingStrategy = Objects.requireNonNull(loadBalancingStrategy, "'loadBalancingStrategy' cannot be" + " null"); return this; } /** * Sets the count used by the receivers to control the number of events each consumer will actively receive and * queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The number of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * * @throws IllegalArgumentException if {@code prefetchCount} is less than 1 or greater than 8000. */ public EventProcessorClientBuilder prefetchCount(int prefetchCount) { eventHubClientBuilder.prefetchCount(prefetchCount); return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. * * @param processEvent The callback that's called when an event is received by this * {@link EventProcessorClient}. * * @return The updated {@link EventProcessorClientBuilder} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent) { return this.processEvent(processEvent, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEvent The callback that's called when an event is received by this {@link EventProcessorClient} * or when the max wait duration has expired. * @param maxWaitTime The max time duration to wait to receive an event before invoking this handler. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEvent(Consumer<EventContext> processEvent, Duration maxWaitTime) { this.processEvent = Objects.requireNonNull(processEvent, "'processEvent' cannot be null"); if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * @param processEventBatch The callback that's called when an event is received by this * {@link EventProcessorClient} or when the max wait duration has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize) { return this.processEventBatch(processEventBatch, maxBatchSize, null); } /** * The function that is called for each event received by this {@link EventProcessorClient}. The input contains the * partition context and the event data. If the max wait time is set, the receive will wait for that duration to * receive an event and if is no event received, the consumer will be invoked with a null event data. * * <!-- src_embed com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * <pre> * TokenCredential credential = new DefaultAzureCredentialBuilder& * * & * & * EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder& * .consumerGroup& * .checkpointStore& * .processEventBatch& * eventBatchContext.getEvents& * System.out.printf& * eventBatchContext.getPartitionContext& * eventData.getSequenceNumber& * & * & * .processError& * System.out.printf& * errorContext.getPartitionContext& * errorContext.getThrowable& * & * .buildEventProcessorClient& * </pre> * <!-- end com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive --> * * @param processEventBatch The callback that's called when an event is received or when the max wait duration * has expired. * @param maxBatchSize The maximum number of events that will be in the list when this callback is invoked. * @param maxWaitTime The max time duration to wait to receive a batch of events upto the max batch size before * invoking this callback. * * @return The updated {@link EventProcessorClient} instance. * * @throws NullPointerException if {@code processEvent} is {@code null}. */ public EventProcessorClientBuilder processEventBatch(Consumer<EventBatchContext> processEventBatch, int maxBatchSize, Duration maxWaitTime) { if (maxBatchSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxBatchSize' should be greater than 0")); } if (maxWaitTime != null && maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxWaitTime' cannot be 0")); } this.processEventBatch = Objects.requireNonNull(processEventBatch, "'processEventBatch' cannot be null"); this.maxBatchSize = maxBatchSize; this.maxWaitTime = maxWaitTime; return this; } /** * The function that is called when an error occurs while processing events. The input contains the partition * information where the error happened. * * @param processError The callback that's called when an error occurs while processing events. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processError(Consumer<ErrorContext> processError) { this.processError = processError; return this; } /** * The function that is called before processing starts for a partition. The input contains the partition * information along with a default starting position for processing events that will be used in the case of a * checkpoint unavailable in {@link CheckpointStore}. Users can update this position if a different starting * position is preferred. * * @param initializePartition The callback that's called before processing starts for a partition * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionInitialization( Consumer<InitializationContext> initializePartition) { this.processPartitionInitialization = initializePartition; return this; } /** * The function that is called when a processing for a partition stops. The input contains the partition information * along with the reason for stopping the event processing for this partition. * * @param closePartition The callback that's called after processing for a partition stops. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder processPartitionClose(Consumer<CloseContext> closePartition) { this.processPartitionClose = closePartition; return this; } /** * Sets whether or not the event processor should request information on the last enqueued event on its associated * partition, and track that information as events are received. * * <p>When information about the partition's last enqueued event is being tracked, each event received from the * Event Hubs service will carry metadata about the partition that it otherwise would not. This results in a small * amount of additional network bandwidth consumption that is generally a favorable trade-off when considered * against periodically making requests for partition properties using the Event Hub client.</p> * * @param trackLastEnqueuedEventProperties {@code true} if the resulting events will keep track of the last * enqueued information for that partition; {@code false} otherwise. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder trackLastEnqueuedEventProperties(boolean trackLastEnqueuedEventProperties) { this.trackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties; return this; } /** * Sets the map containing the event position to use for each partition if a checkpoint for the partition does not * exist in {@link CheckpointStore}. This map is keyed off of the partition id. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialPartitionEventPosition Map of initial event positions for partition ids. * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder initialPartitionEventPosition( Map<String, EventPosition> initialPartitionEventPosition) { this.initialPartitionEventPosition = Objects.requireNonNull(initialPartitionEventPosition, "'initialPartitionEventPosition' cannot be null."); return this; } /** * Sets the default starting position for each partition if a checkpoint for that partition does not exist in the * {@link CheckpointStore}. * * <p> * Only <strong>one overload</strong> of {@code initialPartitionEventPosition} should be used when constructing * an {@link EventProcessorClient}. * </p> * * @param initialEventPositionProvider Function that maps the given {@code partitionId} to an * {@link EventPosition}. * * @return The updated {@link EventProcessorClientBuilder} instance. * @throws NullPointerException if {@code initialEventPositionProvider} is null. */ public EventProcessorClientBuilder initialPartitionEventPosition( Function<String, EventPosition> initialEventPositionProvider) { this.initialEventPositionProvider = Objects.requireNonNull(initialEventPositionProvider, "'initialEventPositionProvider' cannot be null."); return this; } /** * This will create a new {@link EventProcessorClient} configured with the options set in this builder. Each call to * this method will return a new instance of {@link EventProcessorClient}. * * <p> * All partitions processed by this {@link EventProcessorClient} will start processing from * {@link EventPosition * </p> * * @return A new instance of {@link EventProcessorClient}. * * @throws NullPointerException if {@code processEvent} or {@code processError} or {@code checkpointStore} or * {@code consumerGroup} is {@code null}. * @throws IllegalArgumentException if the credentials have not been set using either * {@link * specified but the transport type is not {@link AmqpTransportType * than one overload for {@code setInitialEventPositionProvider} is set. */ private Supplier<PartitionProcessor> getPartitionProcessorSupplier() { return () -> new PartitionProcessor() { @Override public void processEvent(EventContext eventContext) { if (processEvent != null) { processEvent.accept(eventContext); } } @Override public void processEventBatch(EventBatchContext eventBatchContext) { if (processEventBatch != null) { processEventBatch.accept(eventBatchContext); } else { super.processEventBatch(eventBatchContext); } } @Override public void initialize(InitializationContext initializationContext) { if (processPartitionInitialization != null) { processPartitionInitialization.accept(initializationContext); } else { super.initialize(initializationContext); } } @Override public void processError(ErrorContext errorContext) { processError.accept(errorContext); } @Override public void close(CloseContext closeContext) { if (processPartitionClose != null) { processPartitionClose.accept(closeContext); } else { super.close(closeContext); } } }; } }
Maybe we could add a could add a link in the sample to the docs? [this one](https://learn.microsoft.com/azure/ai-services/openai/use-your-data-quickstart) or a link to a guide on how to deploy a Cognitive Search resource, if you know of one.
public static void main(String[] args){ String azureOpenaiKey = "{azure-open-ai-key}"; String endpoint = "{azure-open-ai-endpoint}"; String deploymentOrModelId = "{azure-open-ai-deployment-model-id}"; OpenAIClient client = new OpenAIClientBuilder() .endpoint(endpoint) .credential(new AzureKeyCredential(azureOpenaiKey)) .buildClient(); List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.USER, "How many of our customers are using the latest version of our SDK?")); ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions(chatMessages); String azureSearchEndpoint = "{azure-cognitive-search-endpoint}"; String azureSearchAdminKey = "{azure-cognitive-search-key}"; String azureSearchIndexName = "{azure-cognitive-search-index-name}"; AzureCognitiveSearchChatExtensionConfiguration cognitiveSearchConfiguration = new AzureCognitiveSearchChatExtensionConfiguration( azureSearchEndpoint, azureSearchAdminKey, azureSearchIndexName ); AzureChatExtensionConfiguration extensionConfiguration = new AzureChatExtensionConfiguration( AzureChatExtensionType.AZURE_COGNITIVE_SEARCH, BinaryData.fromObject(cognitiveSearchConfiguration)); chatCompletionsOptions.setDataSources(Arrays.asList(extensionConfiguration)); ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, chatCompletionsOptions); for (ChatChoice choice : chatCompletions.getChoices()) { ChatMessage message = choice.getMessage(); System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole()); System.out.println("Message:"); System.out.println(message.getContent()); } }
AzureChatExtensionConfiguration extensionConfiguration =
public static void main(String[] args){ String azureOpenaiKey = "{azure-open-ai-key}"; String endpoint = "{azure-open-ai-endpoint}"; String deploymentOrModelId = "{azure-open-ai-deployment-model-id}"; OpenAIClient client = new OpenAIClientBuilder() .endpoint(endpoint) .credential(new AzureKeyCredential(azureOpenaiKey)) .buildClient(); List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.USER, "How many of our customers are using the latest version of our SDK?")); ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions(chatMessages); String azureSearchEndpoint = "{azure-cognitive-search-endpoint}"; String azureSearchAdminKey = "{azure-cognitive-search-key}"; String azureSearchIndexName = "{azure-cognitive-search-index-name}"; AzureCognitiveSearchChatExtensionConfiguration cognitiveSearchConfiguration = new AzureCognitiveSearchChatExtensionConfiguration( azureSearchEndpoint, azureSearchAdminKey, azureSearchIndexName ); AzureChatExtensionConfiguration extensionConfiguration = new AzureChatExtensionConfiguration( AzureChatExtensionType.AZURE_COGNITIVE_SEARCH, BinaryData.fromObject(cognitiveSearchConfiguration)); chatCompletionsOptions.setDataSources(Arrays.asList(extensionConfiguration)); ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, chatCompletionsOptions); for (ChatChoice choice : chatCompletions.getChoices()) { ChatMessage message = choice.getMessage(); System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole()); System.out.println("Message:"); System.out.println(message.getContent()); } }
class ChatCompletionsWithYourData { /** * Runs the sample and demonstrates configuration of Azure Cognitive Search as a data source. * * @param args Unused. Arguments to the program. */ }
class ChatCompletionsWithYourData { /** * Runs the sample and demonstrates configuration of Azure Cognitive Search as a data source. * * @param args Unused. Arguments to the program. */ }
I would downgrade this to verbose. I don't remember using it to diagnose issues often.
protected void hookOnSubscribe(Subscription subscription) { logger.atInfo() .addKeyValue("subscription", subscription) .log("Subscription received. Subscribing downstream."); downstream.onSubscribe(this); }
logger.atInfo()
protected void hookOnSubscribe(Subscription subscription) { logger.atVerbose() .addKeyValue("subscription", subscription) .log("Subscription received. Subscribing downstream."); downstream.onSubscribe(this); }
class AutoCompleteSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private final CoreSubscriber<? super ServiceBusMessageContext> downstream; private final Function<ServiceBusMessageContext, Mono<Void>> onComplete; private final Function<ServiceBusMessageContext, Mono<Void>> onAbandon; private final Semaphore semaphore; private final ClientLogger logger; AutoCompleteSubscriber(CoreSubscriber<? super ServiceBusMessageContext> downstream, Semaphore completionLock, Function<ServiceBusMessageContext, Mono<Void>> onComplete, Function<ServiceBusMessageContext, Mono<Void>> onAbandon, ClientLogger logger) { this.downstream = downstream; this.onComplete = onComplete; this.onAbandon = onAbandon; this.semaphore = completionLock; this.logger = logger; } @Override @Override protected void hookOnNext(ServiceBusMessageContext value) { final ServiceBusReceivedMessage message = value.getMessage(); final String sequenceNumber = message != null ? String.valueOf(message.getSequenceNumber()) : "n/a"; logger.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequenceNumber) .log("ON NEXT: Passing message downstream."); try { semaphore.acquire(); } catch (InterruptedException e) { logger.info("Unable to acquire semaphore.", e); } try { downstream.onNext(value); applyWithCatch(onComplete, value, "complete"); } catch (Exception e) { logger.atError() .addKeyValue(SEQUENCE_NUMBER_KEY, sequenceNumber) .log("Error occurred processing message. Abandoning.", e); applyWithCatch(onAbandon, value, "abandon"); } finally { logger.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequenceNumber) .log("ON NEXT: Finished."); semaphore.release(); } } /** * On an error, will pass the exception downstream. * * @param throwable Error to pass downstream. */ @Override protected void hookOnError(Throwable throwable) { logger.error("Error occurred. Passing downstream.", throwable); downstream.onError(throwable); } /** * On the completion. Will pass the complete signal downstream. */ @Override protected void hookOnComplete() { downstream.onComplete(); } @Override public Context currentContext() { return downstream.currentContext(); } /** * Applies a function and catches then logs and closes any exceptions. * * @param function Function to apply. * @param context received message to apply function to. * @param operation The operation name. */ private void applyWithCatch(Function<ServiceBusMessageContext, Mono<Void>> function, ServiceBusMessageContext context, String operation) { if (context.getMessage() != null && context.getMessage().isSettled()) { return; } try { function.apply(context).block(); } catch (Exception e) { logger.atWarning() .addKeyValue("operation", operation) .log("Operation on message failed.", e); upstream().cancel(); onError(e); } } }
class AutoCompleteSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private final CoreSubscriber<? super ServiceBusMessageContext> downstream; private final Function<ServiceBusMessageContext, Mono<Void>> onComplete; private final Function<ServiceBusMessageContext, Mono<Void>> onAbandon; private final Semaphore semaphore; private final ClientLogger logger; AutoCompleteSubscriber(CoreSubscriber<? super ServiceBusMessageContext> downstream, Semaphore completionLock, Function<ServiceBusMessageContext, Mono<Void>> onComplete, Function<ServiceBusMessageContext, Mono<Void>> onAbandon, ClientLogger logger) { this.downstream = downstream; this.onComplete = onComplete; this.onAbandon = onAbandon; this.semaphore = completionLock; this.logger = logger; } @Override @Override protected void hookOnNext(ServiceBusMessageContext value) { final ServiceBusReceivedMessage message = value.getMessage(); final String sequenceNumber = message != null ? String.valueOf(message.getSequenceNumber()) : "n/a"; logger.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequenceNumber) .log("ON NEXT: Passing message downstream."); try { semaphore.acquire(); } catch (InterruptedException e) { logger.info("Unable to acquire semaphore.", e); } try { downstream.onNext(value); applyWithCatch(onComplete, value, "complete"); } catch (Exception e) { logger.atError() .addKeyValue(SEQUENCE_NUMBER_KEY, sequenceNumber) .log("Error occurred processing message. Abandoning.", e); applyWithCatch(onAbandon, value, "abandon"); } finally { logger.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequenceNumber) .log("ON NEXT: Finished."); semaphore.release(); } } /** * On an error, will pass the exception downstream. * * @param throwable Error to pass downstream. */ @Override protected void hookOnError(Throwable throwable) { logger.error("Error occurred. Passing downstream.", throwable); downstream.onError(throwable); } /** * On the completion. Will pass the complete signal downstream. */ @Override protected void hookOnComplete() { downstream.onComplete(); } @Override public Context currentContext() { return downstream.currentContext(); } /** * Applies a function and catches then logs and closes any exceptions. * * @param function Function to apply. * @param context received message to apply function to. * @param operation The operation name. */ private void applyWithCatch(Function<ServiceBusMessageContext, Mono<Void>> function, ServiceBusMessageContext context, String operation) { if (context.getMessage() != null && context.getMessage().isSettled()) { return; } try { function.apply(context).block(); } catch (Exception e) { logger.atWarning() .addKeyValue("operation", operation) .log("Operation on message failed.", e); upstream().cancel(); onError(e); } } }
nit; should we need a "{ }" in the format string for _statusCode_ argument? (or could it be removed since actual status is now an attribute)
private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(amqpMessage); if (statusCode != AmqpResponseCode.OK) { LOGGER.atWarning() .addKeyValue("statusCode", statusCode) .log("AMQP response did not contain OK status code.", statusCode); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { LOGGER.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { LOGGER.atWarning() .addKeyValue("expectedType", Map.class) .addKeyValue("actualType", responseBodyMap.getClass()) .log("AMQP response body is not correct instance."); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(ManagementConstants.MESSAGES); if (messages == null) { LOGGER.atWarning().addKeyValue("expectedKey", ManagementConstants.MESSAGES) .log("AMQP response body did not contain key."); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { LOGGER.atWarning() .addKeyValue("expectedType", Iterable.class) .addKeyValue("actualType", messages.getClass()) .log("Response body contents is not the correct type."); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { LOGGER.atWarning() .addKeyValue("expectedType", Map.class) .addKeyValue("actualType", message.getClass()) .log("Message inside iterable of message is not correct type."); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(ManagementConstants.MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); if (((Map) message).containsKey(ManagementConstants.LOCK_TOKEN_KEY)) { receivedMessage.setLockToken((UUID) ((Map) message).get(ManagementConstants.LOCK_TOKEN_KEY)); } messageList.add(receivedMessage); } return messageList; }
.log("AMQP response did not contain OK status code.", statusCode);
private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(amqpMessage); if (statusCode != AmqpResponseCode.OK) { LOGGER.atWarning() .addKeyValue("statusCode", statusCode) .log("AMQP response did not contain OK status code."); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { LOGGER.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { LOGGER.atWarning() .addKeyValue("expectedType", Map.class) .addKeyValue("actualType", responseBodyMap.getClass()) .log("AMQP response body is not correct instance."); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(ManagementConstants.MESSAGES); if (messages == null) { LOGGER.atWarning().addKeyValue("expectedKey", ManagementConstants.MESSAGES) .log("AMQP response body did not contain key."); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { LOGGER.atWarning() .addKeyValue("expectedType", Iterable.class) .addKeyValue("actualType", messages.getClass()) .log("Response body contents is not the correct type."); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { LOGGER.atWarning() .addKeyValue("expectedType", Map.class) .addKeyValue("actualType", message.getClass()) .log("Message inside iterable of message is not correct type."); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(ManagementConstants.MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); if (((Map) message).containsKey(ManagementConstants.LOCK_TOKEN_KEY)) { receivedMessage.setLockToken((UUID) ((Map) message).get(ManagementConstants.LOCK_TOKEN_KEY)); } messageList.add(receivedMessage); } return messageList; }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; AmqpMessageBodyType brokeredBodyType = brokeredMessage.getRawAmqpMessage().getBody().getBodyType(); final Message amqpMessage = Proton.message(); byte[] body; if (brokeredBodyType == AmqpMessageBodyType.DATA || brokeredBodyType == null) { body = brokeredMessage.getBody().toBytes(); amqpMessage.setBody(new Data(new Binary(body))); } else if (brokeredBodyType == AmqpMessageBodyType.SEQUENCE) { List<Object> sequenceList = brokeredMessage.getRawAmqpMessage().getBody().getSequence(); amqpMessage.setBody(new AmqpSequence(sequenceList)); } else if (brokeredBodyType == AmqpMessageBodyType.VALUE) { amqpMessage.setBody(new AmqpValue(brokeredMessage.getRawAmqpMessage().getBody().getValue())); } if (brokeredMessage.getApplicationProperties() != null) { Map<String, Object> describedTypeMap = convertToDescribedType(brokeredMessage.getApplicationProperties()); amqpMessage.setApplicationProperties(new ApplicationProperties(describedTypeMap)); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getSubject()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final AmqpMessageProperties brokeredProperties = brokeredMessage.getRawAmqpMessage().getProperties(); amqpMessage.setContentEncoding(brokeredProperties.getContentEncoding()); if (brokeredProperties.getGroupSequence() != null) { amqpMessage.setGroupSequence(brokeredProperties.getGroupSequence()); } amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.getProperties().setUserId(new Binary(brokeredProperties.getUserId())); if (brokeredProperties.getAbsoluteExpiryTime() != null) { amqpMessage.getProperties().setAbsoluteExpiryTime(Date.from(brokeredProperties.getAbsoluteExpiryTime() .toInstant())); } if (brokeredProperties.getCreationTime() != null) { amqpMessage.getProperties().setCreationTime(Date.from(brokeredProperties.getCreationTime().toInstant())); } amqpMessage.setFooter(new Footer(brokeredMessage.getRawAmqpMessage().getFooter())); AmqpMessageHeader header = brokeredMessage.getRawAmqpMessage().getHeader(); if (header.getDeliveryCount() != null) { amqpMessage.setDeliveryCount(header.getDeliveryCount()); } if (header.getPriority() != null) { amqpMessage.setPriority(header.getPriority()); } if (header.isDurable() != null) { amqpMessage.setDurable(header.isDurable()); } if (header.isFirstAcquirer() != null) { amqpMessage.setFirstAcquirer(header.isFirstAcquirer()); } if (header.getTimeToLive() != null) { amqpMessage.setTtl(header.getTimeToLive().toMillis()); } final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()), Date.from(brokeredMessage.getScheduledEnqueueTime().toInstant())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_ANNOTATION_NAME.getValue()), brokeredMessage.getPartitionKey()); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); final Map<Symbol, Object> deliveryAnnotationsMap = new HashMap<>(); final Map<String, Object> deliveryAnnotations = brokeredMessage.getRawAmqpMessage() .getDeliveryAnnotations(); for (Map.Entry<String, Object> deliveryEntry : deliveryAnnotations.entrySet()) { deliveryAnnotationsMap.put(Symbol.valueOf(deliveryEntry.getKey()), deliveryEntry.getValue()); } amqpMessage.setDeliveryAnnotations(new DeliveryAnnotations(deliveryAnnotationsMap)); return amqpMessage; } /** * Convert specific type to described type for sending on the wire. * @param propertiesValue application properties set by user which may contain specific type. * @return Map only contains primitive type and described type. */ private static Map<String, Object> convertToDescribedType(Map<String, Object> propertiesValue) { for (Map.Entry<String, Object> entry : propertiesValue.entrySet()) { Object value = entry.getValue(); if (value instanceof URI) { entry.setValue(new UriDescribedType((URI) value)); } else if (value instanceof OffsetDateTime) { entry.setValue(new OffsetDateTimeDescribedType((OffsetDateTime) value)); } else if (value instanceof Duration) { entry.setValue(new DurationDescribedType((Duration) value)); } } return propertiesValue; } /** * Convert described type to origin type. * @param propertiesValue application properties from amqp message may contain described type. * @return Map without described type. */ private static Map<String, Object> convertToOriginType(Map<String, Object> propertiesValue) { for (Map.Entry<String, Object> entry : propertiesValue.entrySet()) { Object value = entry.getValue(); if (value instanceof DescribedType) { entry.setValue(MessageUtils.describedToOrigin((DescribedType) value)); } } return propertiesValue; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == Long.class) { return (List<T>) deserializeListOfLong(message); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } private List<Long> deserializeListOfLong(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.SEQUENCE_NUMBERS); if (expirationListObj instanceof long[]) { return Arrays.stream((long[]) expirationListObj) .boxed() .collect(Collectors.toList()); } } } return Collections.emptyList(); } private List<OffsetDateTime> deserializeListOfOffsetDateTime(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.EXPIRATIONS); if (expirationListObj instanceof Date[]) { return Arrays.stream((Date[]) expirationListObj) .map(date -> date.toInstant().atOffset(ZoneOffset.UTC)) .collect(Collectors.toList()); } } } return Collections.emptyList(); } @SuppressWarnings("rawtypes") private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final Section body = amqpMessage.getBody(); AmqpMessageBody amqpMessageBody; if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); amqpMessageBody = AmqpMessageBody.fromData(messageData.getArray()); } else if (body instanceof AmqpValue) { amqpMessageBody = AmqpMessageBody.fromValue(((AmqpValue) body).getValue()); } else if (body instanceof AmqpSequence) { @SuppressWarnings("unchecked") List<Object> messageData = ((AmqpSequence) body).getValue(); amqpMessageBody = AmqpMessageBody.fromSequence(messageData); } else { LOGGER.atWarning() .addKeyValue("actualType", body.getType()) .log("Message body is not correct. Not setting body contents."); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } } else { LOGGER.atWarning() .addKeyValue("actualType", "null") .log("Message body is not correct. Not setting body contents."); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } final ServiceBusReceivedMessage brokeredMessage = new ServiceBusReceivedMessage(amqpMessageBody); AmqpAnnotatedMessage brokeredAmqpAnnotatedMessage = brokeredMessage.getRawAmqpMessage(); ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { final Map<String, Object> propertiesValue = convertToOriginType(applicationProperties.getValue()); brokeredAmqpAnnotatedMessage.getApplicationProperties().putAll(propertiesValue); } final AmqpMessageHeader brokeredHeader = brokeredAmqpAnnotatedMessage.getHeader(); brokeredHeader.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredHeader.setDeliveryCount(amqpMessage.getDeliveryCount()); brokeredHeader.setDurable(amqpMessage.getHeader().getDurable()); brokeredHeader.setFirstAcquirer(amqpMessage.getHeader().getFirstAcquirer()); brokeredHeader.setPriority(amqpMessage.getPriority()); final Footer footer = amqpMessage.getFooter(); if (footer != null && footer.getValue() != null) { @SuppressWarnings("unchecked") final Map<Symbol, Object> footerValue = footer.getValue(); setValues(footerValue, brokeredAmqpAnnotatedMessage.getFooter()); } final AmqpMessageProperties brokeredProperties = brokeredAmqpAnnotatedMessage.getProperties(); brokeredProperties.setReplyToGroupId(amqpMessage.getReplyToGroupId()); final String replyTo = amqpMessage.getReplyTo(); if (replyTo != null) { brokeredProperties.setReplyTo(new AmqpAddress(amqpMessage.getReplyTo())); } final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredProperties.setMessageId(new AmqpMessageId(messageId.toString())); } brokeredProperties.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredProperties.setCorrelationId(new AmqpMessageId(correlationId.toString())); } final Properties amqpProperties = amqpMessage.getProperties(); if (amqpProperties != null) { final String to = amqpProperties.getTo(); if (to != null) { brokeredProperties.setTo(new AmqpAddress(amqpProperties.getTo())); } if (amqpProperties.getAbsoluteExpiryTime() != null) { brokeredProperties.setAbsoluteExpiryTime(amqpProperties.getAbsoluteExpiryTime().toInstant() .atOffset(ZoneOffset.UTC)); } if (amqpProperties.getCreationTime() != null) { brokeredProperties.setCreationTime(amqpProperties.getCreationTime().toInstant() .atOffset(ZoneOffset.UTC)); } } brokeredProperties.setSubject(amqpMessage.getSubject()); brokeredProperties.setGroupId(amqpMessage.getGroupId()); brokeredProperties.setContentEncoding(amqpMessage.getContentEncoding()); brokeredProperties.setGroupSequence(amqpMessage.getGroupSequence()); brokeredProperties.setUserId(amqpMessage.getUserId()); final DeliveryAnnotations deliveryAnnotations = amqpMessage.getDeliveryAnnotations(); if (deliveryAnnotations != null) { setValues(deliveryAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getDeliveryAnnotations()); } final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { setValues(messageAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getMessageAnnotations()); } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } private void setValues(Map<Symbol, Object> sourceMap, Map<String, Object> targetMap) { if (sourceMap != null) { for (Map.Entry<Symbol, Object> entry : sourceMap.entrySet()) { targetMap.put(entry.getKey().toString(), entry.getValue()); } } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof ServiceBusDescribedType) { ServiceBusDescribedType describedType = (ServiceBusDescribedType) obj; return describedType.size(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; AmqpMessageBodyType brokeredBodyType = brokeredMessage.getRawAmqpMessage().getBody().getBodyType(); final Message amqpMessage = Proton.message(); byte[] body; if (brokeredBodyType == AmqpMessageBodyType.DATA || brokeredBodyType == null) { body = brokeredMessage.getBody().toBytes(); amqpMessage.setBody(new Data(new Binary(body))); } else if (brokeredBodyType == AmqpMessageBodyType.SEQUENCE) { List<Object> sequenceList = brokeredMessage.getRawAmqpMessage().getBody().getSequence(); amqpMessage.setBody(new AmqpSequence(sequenceList)); } else if (brokeredBodyType == AmqpMessageBodyType.VALUE) { amqpMessage.setBody(new AmqpValue(brokeredMessage.getRawAmqpMessage().getBody().getValue())); } if (brokeredMessage.getApplicationProperties() != null) { Map<String, Object> describedTypeMap = convertToDescribedType(brokeredMessage.getApplicationProperties()); amqpMessage.setApplicationProperties(new ApplicationProperties(describedTypeMap)); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getSubject()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final AmqpMessageProperties brokeredProperties = brokeredMessage.getRawAmqpMessage().getProperties(); amqpMessage.setContentEncoding(brokeredProperties.getContentEncoding()); if (brokeredProperties.getGroupSequence() != null) { amqpMessage.setGroupSequence(brokeredProperties.getGroupSequence()); } amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.getProperties().setUserId(new Binary(brokeredProperties.getUserId())); if (brokeredProperties.getAbsoluteExpiryTime() != null) { amqpMessage.getProperties().setAbsoluteExpiryTime(Date.from(brokeredProperties.getAbsoluteExpiryTime() .toInstant())); } if (brokeredProperties.getCreationTime() != null) { amqpMessage.getProperties().setCreationTime(Date.from(brokeredProperties.getCreationTime().toInstant())); } amqpMessage.setFooter(new Footer(brokeredMessage.getRawAmqpMessage().getFooter())); AmqpMessageHeader header = brokeredMessage.getRawAmqpMessage().getHeader(); if (header.getDeliveryCount() != null) { amqpMessage.setDeliveryCount(header.getDeliveryCount()); } if (header.getPriority() != null) { amqpMessage.setPriority(header.getPriority()); } if (header.isDurable() != null) { amqpMessage.setDurable(header.isDurable()); } if (header.isFirstAcquirer() != null) { amqpMessage.setFirstAcquirer(header.isFirstAcquirer()); } if (header.getTimeToLive() != null) { amqpMessage.setTtl(header.getTimeToLive().toMillis()); } final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()), Date.from(brokeredMessage.getScheduledEnqueueTime().toInstant())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_ANNOTATION_NAME.getValue()), brokeredMessage.getPartitionKey()); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); final Map<Symbol, Object> deliveryAnnotationsMap = new HashMap<>(); final Map<String, Object> deliveryAnnotations = brokeredMessage.getRawAmqpMessage() .getDeliveryAnnotations(); for (Map.Entry<String, Object> deliveryEntry : deliveryAnnotations.entrySet()) { deliveryAnnotationsMap.put(Symbol.valueOf(deliveryEntry.getKey()), deliveryEntry.getValue()); } amqpMessage.setDeliveryAnnotations(new DeliveryAnnotations(deliveryAnnotationsMap)); return amqpMessage; } /** * Convert specific type to described type for sending on the wire. * @param propertiesValue application properties set by user which may contain specific type. * @return Map only contains primitive type and described type. */ private static Map<String, Object> convertToDescribedType(Map<String, Object> propertiesValue) { for (Map.Entry<String, Object> entry : propertiesValue.entrySet()) { Object value = entry.getValue(); if (value instanceof URI) { entry.setValue(new UriDescribedType((URI) value)); } else if (value instanceof OffsetDateTime) { entry.setValue(new OffsetDateTimeDescribedType((OffsetDateTime) value)); } else if (value instanceof Duration) { entry.setValue(new DurationDescribedType((Duration) value)); } } return propertiesValue; } /** * Convert described type to origin type. * @param propertiesValue application properties from amqp message may contain described type. * @return Map without described type. */ private static Map<String, Object> convertToOriginType(Map<String, Object> propertiesValue) { for (Map.Entry<String, Object> entry : propertiesValue.entrySet()) { Object value = entry.getValue(); if (value instanceof DescribedType) { entry.setValue(MessageUtils.describedToOrigin((DescribedType) value)); } } return propertiesValue; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == Long.class) { return (List<T>) deserializeListOfLong(message); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } private List<Long> deserializeListOfLong(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.SEQUENCE_NUMBERS); if (expirationListObj instanceof long[]) { return Arrays.stream((long[]) expirationListObj) .boxed() .collect(Collectors.toList()); } } } return Collections.emptyList(); } private List<OffsetDateTime> deserializeListOfOffsetDateTime(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.EXPIRATIONS); if (expirationListObj instanceof Date[]) { return Arrays.stream((Date[]) expirationListObj) .map(date -> date.toInstant().atOffset(ZoneOffset.UTC)) .collect(Collectors.toList()); } } } return Collections.emptyList(); } @SuppressWarnings("rawtypes") private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final Section body = amqpMessage.getBody(); AmqpMessageBody amqpMessageBody; if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); amqpMessageBody = AmqpMessageBody.fromData(messageData.getArray()); } else if (body instanceof AmqpValue) { amqpMessageBody = AmqpMessageBody.fromValue(((AmqpValue) body).getValue()); } else if (body instanceof AmqpSequence) { @SuppressWarnings("unchecked") List<Object> messageData = ((AmqpSequence) body).getValue(); amqpMessageBody = AmqpMessageBody.fromSequence(messageData); } else { LOGGER.atWarning() .addKeyValue("actualType", body.getType()) .log("Message body is not correct. Not setting body contents."); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } } else { LOGGER.atWarning() .addKeyValue("actualType", "null") .log("Message body is not correct. Not setting body contents."); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } final ServiceBusReceivedMessage brokeredMessage = new ServiceBusReceivedMessage(amqpMessageBody); AmqpAnnotatedMessage brokeredAmqpAnnotatedMessage = brokeredMessage.getRawAmqpMessage(); ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { final Map<String, Object> propertiesValue = convertToOriginType(applicationProperties.getValue()); brokeredAmqpAnnotatedMessage.getApplicationProperties().putAll(propertiesValue); } final AmqpMessageHeader brokeredHeader = brokeredAmqpAnnotatedMessage.getHeader(); brokeredHeader.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredHeader.setDeliveryCount(amqpMessage.getDeliveryCount()); brokeredHeader.setDurable(amqpMessage.getHeader().getDurable()); brokeredHeader.setFirstAcquirer(amqpMessage.getHeader().getFirstAcquirer()); brokeredHeader.setPriority(amqpMessage.getPriority()); final Footer footer = amqpMessage.getFooter(); if (footer != null && footer.getValue() != null) { @SuppressWarnings("unchecked") final Map<Symbol, Object> footerValue = footer.getValue(); setValues(footerValue, brokeredAmqpAnnotatedMessage.getFooter()); } final AmqpMessageProperties brokeredProperties = brokeredAmqpAnnotatedMessage.getProperties(); brokeredProperties.setReplyToGroupId(amqpMessage.getReplyToGroupId()); final String replyTo = amqpMessage.getReplyTo(); if (replyTo != null) { brokeredProperties.setReplyTo(new AmqpAddress(amqpMessage.getReplyTo())); } final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredProperties.setMessageId(new AmqpMessageId(messageId.toString())); } brokeredProperties.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredProperties.setCorrelationId(new AmqpMessageId(correlationId.toString())); } final Properties amqpProperties = amqpMessage.getProperties(); if (amqpProperties != null) { final String to = amqpProperties.getTo(); if (to != null) { brokeredProperties.setTo(new AmqpAddress(amqpProperties.getTo())); } if (amqpProperties.getAbsoluteExpiryTime() != null) { brokeredProperties.setAbsoluteExpiryTime(amqpProperties.getAbsoluteExpiryTime().toInstant() .atOffset(ZoneOffset.UTC)); } if (amqpProperties.getCreationTime() != null) { brokeredProperties.setCreationTime(amqpProperties.getCreationTime().toInstant() .atOffset(ZoneOffset.UTC)); } } brokeredProperties.setSubject(amqpMessage.getSubject()); brokeredProperties.setGroupId(amqpMessage.getGroupId()); brokeredProperties.setContentEncoding(amqpMessage.getContentEncoding()); brokeredProperties.setGroupSequence(amqpMessage.getGroupSequence()); brokeredProperties.setUserId(amqpMessage.getUserId()); final DeliveryAnnotations deliveryAnnotations = amqpMessage.getDeliveryAnnotations(); if (deliveryAnnotations != null) { setValues(deliveryAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getDeliveryAnnotations()); } final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { setValues(messageAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getMessageAnnotations()); } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } private void setValues(Map<Symbol, Object> sourceMap, Map<String, Object> targetMap) { if (sourceMap != null) { for (Map.Entry<Symbol, Object> entry : sourceMap.entrySet()) { targetMap.put(entry.getKey().toString(), entry.getValue()); } } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof ServiceBusDescribedType) { ServiceBusDescribedType describedType = (ServiceBusDescribedType) obj; return describedType.size(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
Nice!. While the Message::correlationId is _Object_, the actual type in case of Az Messaging Services is always _UnsignedLong_. So this is a nice improvement saving us from unnecessary conversion to String and then back to long in that common cases :+1:
private void settleMessage(Message message) { UnsignedLong correlationId; if (message.getCorrelationId() instanceof UnsignedLong) { correlationId = (UnsignedLong) message.getCorrelationId(); } else { String id = String.valueOf(message.getCorrelationId()); correlationId = UnsignedLong.valueOf(id); } final MonoSink<Message> sink = unconfirmedSends.remove(correlationId); if (sink == null) { logger.atWarning() .addKeyValue("messageId", message.getCorrelationId()) .log("Received delivery without pending message."); return; } recordDelivery(getSinkContext(sink), message); sink.success(message); }
if (message.getCorrelationId() instanceof UnsignedLong) {
private void settleMessage(Message message) { UnsignedLong correlationId; if (message.getCorrelationId() instanceof UnsignedLong) { correlationId = (UnsignedLong) message.getCorrelationId(); } else { String id = String.valueOf(message.getCorrelationId()); correlationId = UnsignedLong.valueOf(id); } final MonoSink<Message> sink = unconfirmedSends.remove(correlationId); if (sink == null) { logger.atWarning() .addKeyValue("messageId", message.getCorrelationId()) .log("Received delivery without pending message."); return; } recordDelivery(getSinkContext(sink), message); sink.success(message); }
class RequestResponseChannel implements AsyncCloseable { private static final String MANAGEMENT_OPERATION_KEY = "operation"; private final ClientLogger logger; private final Sender sendLink; private final Receiver receiveLink; private final SendLinkHandler sendLinkHandler; private final ReceiveLinkHandler receiveLinkHandler; private final SenderSettleMode senderSettleMode; private final Sinks.Many<AmqpEndpointState> endpointStates = Sinks.many().multicast().onBackpressureBuffer(); private volatile AmqpEndpointState sendLinkState; private volatile AmqpEndpointState receiveLinkState; private final AtomicLong requestId = new AtomicLong(0); private final ConcurrentSkipListMap<UnsignedLong, MonoSink<Message>> unconfirmedSends = new ConcurrentSkipListMap<>(); private final AtomicInteger pendingLinkTerminations = new AtomicInteger(2); private final Sinks.One<Void> closeMono = Sinks.one(); private final AtomicBoolean hasError = new AtomicBoolean(); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final Disposable.Composite subscriptions; private final AmqpRetryOptions retryOptions; private final String replyTo; private final String activeEndpointTimeoutMessage; private final MessageSerializer messageSerializer; private final ReactorProvider provider; private final AmqpMetricsProvider metricsProvider; private static final String START_SEND_TIME_CONTEXT_KEY = "send-start-time"; private static final String OPERATION_CONTEXT_KEY = "amqpOperation"; /** * Creates a new instance of {@link RequestResponseChannel} to send and receive responses from the {@code * entityPath} in the message broker. * * @param connectionId Identifier of the connection. * @param fullyQualifiedNamespace Fully qualified namespace for the the host. * @param linkName Name of the link. * @param entityPath Address in the message broker to send message to. * @param session Reactor session associated with this link. * @param retryOptions Retry options to use for sending the request response. * @param handlerProvider Provides handlers that interact with proton-j's reactor. * @param provider The reactor provider that the request will be sent with. * @param senderSettleMode to set as {@link SenderSettleMode} on sender. * @param receiverSettleMode to set as {@link ReceiverSettleMode} on receiver. * * @throws RuntimeException if the send/receive links could not be locally scheduled to open. */ protected RequestResponseChannel(AmqpConnection amqpConnection, String connectionId, String fullyQualifiedNamespace, String linkName, String entityPath, Session session, AmqpRetryOptions retryOptions, ReactorHandlerProvider handlerProvider, ReactorProvider provider, MessageSerializer messageSerializer, SenderSettleMode senderSettleMode, ReceiverSettleMode receiverSettleMode, AmqpMetricsProvider metricsProvider) { Map<String, Object> loggingContext = createContextWithConnectionId(connectionId); loggingContext.put(LINK_NAME_KEY, linkName); this.logger = new ClientLogger(RequestResponseChannel.class, loggingContext); this.retryOptions = retryOptions; this.provider = provider; this.senderSettleMode = senderSettleMode; this.activeEndpointTimeoutMessage = String.format( "RequestResponseChannel connectionId[%s], linkName[%s]: Waiting for send and receive handler to be ACTIVE", connectionId, linkName); this.replyTo = entityPath.replace("$", "") + "-client-reply-to"; this.messageSerializer = messageSerializer; this.sendLink = session.sender(linkName + ":sender"); final Target senderTarget = new Target(); senderTarget.setAddress(entityPath); this.sendLink.setTarget(senderTarget); this.sendLink.setSource(new Source()); this.sendLink.setSenderSettleMode(senderSettleMode); this.sendLinkHandler = handlerProvider.createSendLinkHandler(connectionId, fullyQualifiedNamespace, linkName, entityPath); BaseHandler.setHandler(sendLink, sendLinkHandler); this.receiveLink = session.receiver(linkName + ":receiver"); final Source receiverSource = new Source(); receiverSource.setAddress(entityPath); this.receiveLink.setSource(receiverSource); final Target receiverTarget = new Target(); receiverTarget.setAddress(replyTo); this.receiveLink.setTarget(receiverTarget); this.receiveLink.setSenderSettleMode(senderSettleMode); this.receiveLink.setReceiverSettleMode(receiverSettleMode); this.receiveLinkHandler = handlerProvider.createReceiveLinkHandler(connectionId, fullyQualifiedNamespace, linkName, entityPath); BaseHandler.setHandler(receiveLink, receiveLinkHandler); this.metricsProvider = metricsProvider; this.subscriptions = Disposables.composite( receiveLinkHandler.getDeliveredMessages() .map(this::decodeDelivery) .subscribe(message -> { logger.atVerbose() .addKeyValue("messageId", message.getCorrelationId()) .log("Settling message."); settleMessage(message); }), receiveLinkHandler.getEndpointStates().subscribe(state -> { updateEndpointState(null, AmqpEndpointStateUtil.getConnectionState(state)); }, error -> { handleError(error, "Error in ReceiveLinkHandler."); onTerminalState("ReceiveLinkHandler"); }, () -> { closeAsync().subscribe(); onTerminalState("ReceiveLinkHandler"); }), sendLinkHandler.getEndpointStates().subscribe(state -> { updateEndpointState(AmqpEndpointStateUtil.getConnectionState(state), null); }, error -> { handleError(error, "Error in SendLinkHandler."); onTerminalState("SendLinkHandler"); }, () -> { closeAsync().subscribe(); onTerminalState("SendLinkHandler"); }), amqpConnection.getShutdownSignals().next().flatMap(signal -> { logger.verbose("Shutdown signal received."); return closeAsync(); }).subscribe() ); try { this.provider.getReactorDispatcher().invoke(() -> { this.sendLink.open(); this.receiveLink.open(); }); } catch (IOException | RejectedExecutionException e) { throw logger.logExceptionAsWarning(new RuntimeException("Unable to open send and receive link.", e)); } } /** * Gets the endpoint states for the request-response-channel. * * @return The endpoint states for the request-response-channel. */ public Flux<AmqpEndpointState> getEndpointStates() { return endpointStates.asFlux(); } @Override public Mono<Void> closeAsync() { final Mono<Void> closeOperationWithTimeout = closeMono.asMono() .timeout(retryOptions.getTryTimeout()) .onErrorResume(TimeoutException.class, error -> { return Mono.fromRunnable(() -> { logger.info("Timed out waiting for RequestResponseChannel to complete closing. Manually closing."); onTerminalState("SendLinkHandler"); onTerminalState("ReceiveLinkHandler"); }); }) .subscribeOn(Schedulers.boundedElastic()); if (isDisposed.getAndSet(true)) { logger.verbose("Channel already closed."); return closeOperationWithTimeout; } logger.verbose("Closing request/response channel."); return Mono.fromRunnable(() -> { try { provider.getReactorDispatcher().invoke(() -> { logger.verbose("Closing send link and receive link."); sendLink.close(); receiveLink.close(); }); } catch (IOException | RejectedExecutionException e) { logger.info("Unable to schedule close work. Closing manually."); sendLink.close(); receiveLink.close(); } }).subscribeOn(Schedulers.boundedElastic()).then(closeOperationWithTimeout); } public boolean isDisposed() { return isDisposed.get(); } /** * Sends a message to the message broker using the {@code dispatcher} and gets the response. * * @param message AMQP message to send. * * @return An AMQP message representing the service's response to the message. */ public Mono<Message> sendWithAck(final Message message) { return sendWithAck(message, null); } /** * Sends a message to the message broker using the {@code dispatcher} and gets the response. * * @param message AMQP message to send. * @param deliveryState Delivery state to be sent to service bus with message. * * @return An AMQP message representing the service's response to the message. */ public Mono<Message> sendWithAck(final Message message, DeliveryState deliveryState) { if (isDisposed()) { return monoError(logger, new RequestResponseChannelClosedException()); } if (message == null) { return monoError(logger, new NullPointerException("message cannot be null")); } if (message.getMessageId() != null) { return monoError(logger, new IllegalArgumentException("message.getMessageId() should be null")); } if (message.getReplyTo() != null) { return monoError(logger, new IllegalArgumentException("message.getReplyTo() should be null")); } final UnsignedLong messageId = UnsignedLong.valueOf(requestId.incrementAndGet()); message.setMessageId(messageId); message.setReplyTo(replyTo); final Mono<Void> onActiveEndpoints = Mono.when( sendLinkHandler.getEndpointStates().takeUntil(x -> x == EndpointState.ACTIVE), receiveLinkHandler.getEndpointStates().takeUntil(x -> x == EndpointState.ACTIVE)); return RetryUtil.withRetry(onActiveEndpoints, retryOptions, activeEndpointTimeoutMessage) .then(captureStartTime(message, Mono.create(sink -> { try { logger.atVerbose() .addKeyValue("messageId", message.getCorrelationId()) .log("Scheduling on dispatcher."); unconfirmedSends.putIfAbsent(messageId, sink); provider.getReactorDispatcher().invoke(() -> { if (isDisposed()) { sink.error(new RequestResponseChannelClosedException(sendLink.getLocalState(), receiveLink.getLocalState())); return; } final Delivery delivery = sendLink.delivery(UUID.randomUUID().toString() .replace("-", "").getBytes(UTF_8)); if (deliveryState != null) { logger.atVerbose() .addKeyValue("state", deliveryState) .log("Setting delivery state."); delivery.setMessageFormat(DeliveryImpl.DEFAULT_MESSAGE_FORMAT); delivery.disposition(deliveryState); } final int payloadSize = messageSerializer.getSize(message) + ClientConstants.MAX_AMQP_HEADER_SIZE_BYTES; final byte[] bytes = new byte[payloadSize]; final int encodedSize = message.encode(bytes, 0, payloadSize); receiveLink.flow(1); sendLink.send(bytes, 0, encodedSize); delivery.settle(); sendLink.advance(); }); } catch (IOException | RejectedExecutionException e) { recordDelivery(getSinkContext(sink), null); sink.error(e); } }))); } /** * Gets the error context for the channel. * * @return The error context for the channel. */ public AmqpErrorContext getErrorContext() { return receiveLinkHandler.getErrorContext(receiveLink); } protected Message decodeDelivery(Delivery delivery) { final Message response = Proton.message(); final int msgSize = delivery.pending(); final byte[] buffer = new byte[msgSize]; final int read = receiveLink.recv(buffer, 0, msgSize); response.decode(buffer, 0, read); if (this.senderSettleMode == SenderSettleMode.SETTLED) { delivery.disposition(Accepted.getInstance()); delivery.settle(); } return response; } private void handleError(Throwable error, String message) { if (hasError.getAndSet(true)) { return; } logger.atWarning() .log("{} Disposing unconfirmed sends.", message, error); endpointStates.emitError(error, (signalType, emitResult) -> { addSignalTypeAndResult(logger.atWarning(), signalType, emitResult) .log("Could not emit error to sink."); return false; }); terminateUnconfirmedSends(error); closeAsync().subscribe(); } private void onTerminalState(String handlerName) { if (pendingLinkTerminations.get() <= 0) { logger.atVerbose() .log("Already disposed send/receive links."); return; } final int remaining = pendingLinkTerminations.decrementAndGet(); logger.verbose("{} disposed. Remaining: {}", handlerName, remaining); if (remaining == 0) { subscriptions.dispose(); terminateUnconfirmedSends(new AmqpException(true, "The RequestResponseChannel didn't receive the acknowledgment for the send due receive link termination.", null)); endpointStates.emitComplete(((signalType, emitResult) -> onEmitSinkFailure(signalType, emitResult, "Could not emit complete signal."))); closeMono.emitEmpty((signalType, emitResult) -> onEmitSinkFailure(signalType, emitResult, handlerName + ". Error closing mono.")); } } private boolean onEmitSinkFailure(SignalType signalType, Sinks.EmitResult emitResult, String message) { addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult) .log(message); return false; } private synchronized void updateEndpointState(AmqpEndpointState sendLinkState, AmqpEndpointState receiveLinkState) { if (sendLinkState != null) { this.sendLinkState = sendLinkState; } else if (receiveLinkState != null) { this.receiveLinkState = receiveLinkState; } logger.atVerbose() .addKeyValue("sendState", this.sendLinkState) .addKeyValue("receiveState", this.receiveLinkState) .log("Updating endpoint states."); if (this.sendLinkState == this.receiveLinkState) { this.endpointStates.emitNext(this.sendLinkState, Sinks.EmitFailureHandler.FAIL_FAST); } } private void terminateUnconfirmedSends(Throwable error) { logger.verbose("Terminating {} unconfirmed sends (reason: {}).", unconfirmedSends.size(), error.getMessage()); Map.Entry<UnsignedLong, MonoSink<Message>> next; int count = 0; while ((next = unconfirmedSends.pollFirstEntry()) != null) { MonoSink<Message> sink = next.getValue(); recordDelivery(getSinkContext(sink), null); sink.error(error); count++; } logger.atVerbose() .log("completed the termination of {} unconfirmed sends (reason: {}).", count, error.getMessage()); } /** * Captures current time in mono context - used to report send metric */ private Mono<Message> captureStartTime(Message toSend, Mono<Message> publisher) { if (metricsProvider.isRequestResponseDurationEnabled()) { String operationName = "unknown"; if (toSend != null && toSend.getApplicationProperties() != null && toSend.getApplicationProperties().getValue() != null) { Map<String, Object> properties = toSend.getApplicationProperties().getValue(); Object operationObj = properties.get(MANAGEMENT_OPERATION_KEY); if (operationObj instanceof String) { operationName = (String) operationObj; } } return publisher.contextWrite( Context.of(START_SEND_TIME_CONTEXT_KEY, Instant.now()).put(OPERATION_CONTEXT_KEY, operationName)); } return publisher; } @SuppressWarnings("deprecation") private static ContextView getSinkContext(MonoSink<?> sink) { return sink.currentContext(); } /** * Records send call duration metric. **/ private void recordDelivery(ContextView context, Message response) { if (metricsProvider.isRequestResponseDurationEnabled()) { Object startTimestamp = context.getOrDefault(START_SEND_TIME_CONTEXT_KEY, null); Object operationName = context.getOrDefault(OPERATION_CONTEXT_KEY, null); AmqpResponseCode responseCode = response == null ? null : RequestResponseUtils.getStatusCode(response); if (startTimestamp instanceof Instant && operationName instanceof String) { metricsProvider.recordRequestResponseDuration( ((Instant) startTimestamp).toEpochMilli(), (String) operationName, responseCode); } } } }
class RequestResponseChannel implements AsyncCloseable { private static final String MANAGEMENT_OPERATION_KEY = "operation"; private final ClientLogger logger; private final Sender sendLink; private final Receiver receiveLink; private final SendLinkHandler sendLinkHandler; private final ReceiveLinkHandler receiveLinkHandler; private final SenderSettleMode senderSettleMode; private final Sinks.Many<AmqpEndpointState> endpointStates = Sinks.many().multicast().onBackpressureBuffer(); private volatile AmqpEndpointState sendLinkState; private volatile AmqpEndpointState receiveLinkState; private final AtomicLong requestId = new AtomicLong(0); private final ConcurrentSkipListMap<UnsignedLong, MonoSink<Message>> unconfirmedSends = new ConcurrentSkipListMap<>(); private final AtomicInteger pendingLinkTerminations = new AtomicInteger(2); private final Sinks.One<Void> closeMono = Sinks.one(); private final AtomicBoolean hasError = new AtomicBoolean(); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final Disposable.Composite subscriptions; private final AmqpRetryOptions retryOptions; private final String replyTo; private final String activeEndpointTimeoutMessage; private final MessageSerializer messageSerializer; private final ReactorProvider provider; private final AmqpMetricsProvider metricsProvider; private static final String START_SEND_TIME_CONTEXT_KEY = "send-start-time"; private static final String OPERATION_CONTEXT_KEY = "amqpOperation"; /** * Creates a new instance of {@link RequestResponseChannel} to send and receive responses from the {@code * entityPath} in the message broker. * * @param connectionId Identifier of the connection. * @param fullyQualifiedNamespace Fully qualified namespace for the the host. * @param linkName Name of the link. * @param entityPath Address in the message broker to send message to. * @param session Reactor session associated with this link. * @param retryOptions Retry options to use for sending the request response. * @param handlerProvider Provides handlers that interact with proton-j's reactor. * @param provider The reactor provider that the request will be sent with. * @param senderSettleMode to set as {@link SenderSettleMode} on sender. * @param receiverSettleMode to set as {@link ReceiverSettleMode} on receiver. * * @throws RuntimeException if the send/receive links could not be locally scheduled to open. */ protected RequestResponseChannel(AmqpConnection amqpConnection, String connectionId, String fullyQualifiedNamespace, String linkName, String entityPath, Session session, AmqpRetryOptions retryOptions, ReactorHandlerProvider handlerProvider, ReactorProvider provider, MessageSerializer messageSerializer, SenderSettleMode senderSettleMode, ReceiverSettleMode receiverSettleMode, AmqpMetricsProvider metricsProvider) { Map<String, Object> loggingContext = createContextWithConnectionId(connectionId); loggingContext.put(LINK_NAME_KEY, linkName); this.logger = new ClientLogger(RequestResponseChannel.class, loggingContext); this.retryOptions = retryOptions; this.provider = provider; this.senderSettleMode = senderSettleMode; this.activeEndpointTimeoutMessage = String.format( "RequestResponseChannel connectionId[%s], linkName[%s]: Waiting for send and receive handler to be ACTIVE", connectionId, linkName); this.replyTo = entityPath.replace("$", "") + "-client-reply-to"; this.messageSerializer = messageSerializer; this.sendLink = session.sender(linkName + ":sender"); final Target senderTarget = new Target(); senderTarget.setAddress(entityPath); this.sendLink.setTarget(senderTarget); this.sendLink.setSource(new Source()); this.sendLink.setSenderSettleMode(senderSettleMode); this.sendLinkHandler = handlerProvider.createSendLinkHandler(connectionId, fullyQualifiedNamespace, linkName, entityPath); BaseHandler.setHandler(sendLink, sendLinkHandler); this.receiveLink = session.receiver(linkName + ":receiver"); final Source receiverSource = new Source(); receiverSource.setAddress(entityPath); this.receiveLink.setSource(receiverSource); final Target receiverTarget = new Target(); receiverTarget.setAddress(replyTo); this.receiveLink.setTarget(receiverTarget); this.receiveLink.setSenderSettleMode(senderSettleMode); this.receiveLink.setReceiverSettleMode(receiverSettleMode); this.receiveLinkHandler = handlerProvider.createReceiveLinkHandler(connectionId, fullyQualifiedNamespace, linkName, entityPath); BaseHandler.setHandler(receiveLink, receiveLinkHandler); this.metricsProvider = metricsProvider; this.subscriptions = Disposables.composite( receiveLinkHandler.getDeliveredMessages() .map(this::decodeDelivery) .subscribe(message -> { logger.atVerbose() .addKeyValue("messageId", message.getCorrelationId()) .log("Settling message."); settleMessage(message); }), receiveLinkHandler.getEndpointStates().subscribe(state -> { updateEndpointState(null, AmqpEndpointStateUtil.getConnectionState(state)); }, error -> { handleError(error, "Error in ReceiveLinkHandler."); onTerminalState("ReceiveLinkHandler"); }, () -> { closeAsync().subscribe(); onTerminalState("ReceiveLinkHandler"); }), sendLinkHandler.getEndpointStates().subscribe(state -> { updateEndpointState(AmqpEndpointStateUtil.getConnectionState(state), null); }, error -> { handleError(error, "Error in SendLinkHandler."); onTerminalState("SendLinkHandler"); }, () -> { closeAsync().subscribe(); onTerminalState("SendLinkHandler"); }), amqpConnection.getShutdownSignals().next().flatMap(signal -> { logger.verbose("Shutdown signal received."); return closeAsync(); }).subscribe() ); try { this.provider.getReactorDispatcher().invoke(() -> { this.sendLink.open(); this.receiveLink.open(); }); } catch (IOException | RejectedExecutionException e) { throw logger.logExceptionAsWarning(new RuntimeException("Unable to open send and receive link.", e)); } } /** * Gets the endpoint states for the request-response-channel. * * @return The endpoint states for the request-response-channel. */ public Flux<AmqpEndpointState> getEndpointStates() { return endpointStates.asFlux(); } @Override public Mono<Void> closeAsync() { final Mono<Void> closeOperationWithTimeout = closeMono.asMono() .timeout(retryOptions.getTryTimeout()) .onErrorResume(TimeoutException.class, error -> { return Mono.fromRunnable(() -> { logger.info("Timed out waiting for RequestResponseChannel to complete closing. Manually closing."); onTerminalState("SendLinkHandler"); onTerminalState("ReceiveLinkHandler"); }); }) .subscribeOn(Schedulers.boundedElastic()); if (isDisposed.getAndSet(true)) { logger.verbose("Channel already closed."); return closeOperationWithTimeout; } logger.verbose("Closing request/response channel."); return Mono.fromRunnable(() -> { try { provider.getReactorDispatcher().invoke(() -> { logger.verbose("Closing send link and receive link."); sendLink.close(); receiveLink.close(); }); } catch (IOException | RejectedExecutionException e) { logger.info("Unable to schedule close work. Closing manually."); sendLink.close(); receiveLink.close(); } }).subscribeOn(Schedulers.boundedElastic()).then(closeOperationWithTimeout); } public boolean isDisposed() { return isDisposed.get(); } /** * Sends a message to the message broker using the {@code dispatcher} and gets the response. * * @param message AMQP message to send. * * @return An AMQP message representing the service's response to the message. */ public Mono<Message> sendWithAck(final Message message) { return sendWithAck(message, null); } /** * Sends a message to the message broker using the {@code dispatcher} and gets the response. * * @param message AMQP message to send. * @param deliveryState Delivery state to be sent to service bus with message. * * @return An AMQP message representing the service's response to the message. */ public Mono<Message> sendWithAck(final Message message, DeliveryState deliveryState) { if (isDisposed()) { return monoError(logger, new RequestResponseChannelClosedException()); } if (message == null) { return monoError(logger, new NullPointerException("message cannot be null")); } if (message.getMessageId() != null) { return monoError(logger, new IllegalArgumentException("message.getMessageId() should be null")); } if (message.getReplyTo() != null) { return monoError(logger, new IllegalArgumentException("message.getReplyTo() should be null")); } final UnsignedLong messageId = UnsignedLong.valueOf(requestId.incrementAndGet()); message.setMessageId(messageId); message.setReplyTo(replyTo); final Mono<Void> onActiveEndpoints = Mono.when( sendLinkHandler.getEndpointStates().takeUntil(x -> x == EndpointState.ACTIVE), receiveLinkHandler.getEndpointStates().takeUntil(x -> x == EndpointState.ACTIVE)); return RetryUtil.withRetry(onActiveEndpoints, retryOptions, activeEndpointTimeoutMessage) .then(captureStartTime(message, Mono.create(sink -> { try { logger.atVerbose() .addKeyValue("messageId", message.getCorrelationId()) .log("Scheduling on dispatcher."); unconfirmedSends.putIfAbsent(messageId, sink); provider.getReactorDispatcher().invoke(() -> { if (isDisposed()) { sink.error(new RequestResponseChannelClosedException(sendLink.getLocalState(), receiveLink.getLocalState())); return; } final Delivery delivery = sendLink.delivery(UUID.randomUUID().toString() .replace("-", "").getBytes(UTF_8)); if (deliveryState != null) { logger.atVerbose() .addKeyValue("state", deliveryState) .log("Setting delivery state."); delivery.setMessageFormat(DeliveryImpl.DEFAULT_MESSAGE_FORMAT); delivery.disposition(deliveryState); } final int payloadSize = messageSerializer.getSize(message) + ClientConstants.MAX_AMQP_HEADER_SIZE_BYTES; final byte[] bytes = new byte[payloadSize]; final int encodedSize = message.encode(bytes, 0, payloadSize); receiveLink.flow(1); sendLink.send(bytes, 0, encodedSize); delivery.settle(); sendLink.advance(); }); } catch (IOException | RejectedExecutionException e) { recordDelivery(getSinkContext(sink), null); sink.error(e); } }))); } /** * Gets the error context for the channel. * * @return The error context for the channel. */ public AmqpErrorContext getErrorContext() { return receiveLinkHandler.getErrorContext(receiveLink); } protected Message decodeDelivery(Delivery delivery) { final Message response = Proton.message(); final int msgSize = delivery.pending(); final byte[] buffer = new byte[msgSize]; final int read = receiveLink.recv(buffer, 0, msgSize); response.decode(buffer, 0, read); if (this.senderSettleMode == SenderSettleMode.SETTLED) { delivery.disposition(Accepted.getInstance()); delivery.settle(); } return response; } private void handleError(Throwable error, String message) { if (hasError.getAndSet(true)) { return; } logger.atWarning() .log("{} Disposing unconfirmed sends.", message, error); endpointStates.emitError(error, (signalType, emitResult) -> { addSignalTypeAndResult(logger.atWarning(), signalType, emitResult) .log("Could not emit error to sink."); return false; }); terminateUnconfirmedSends(error); closeAsync().subscribe(); } private void onTerminalState(String handlerName) { if (pendingLinkTerminations.get() <= 0) { logger.atVerbose() .log("Already disposed send/receive links."); return; } final int remaining = pendingLinkTerminations.decrementAndGet(); logger.verbose("{} disposed. Remaining: {}", handlerName, remaining); if (remaining == 0) { subscriptions.dispose(); terminateUnconfirmedSends(new AmqpException(true, "The RequestResponseChannel didn't receive the acknowledgment for the send due receive link termination.", null)); endpointStates.emitComplete(((signalType, emitResult) -> onEmitSinkFailure(signalType, emitResult, "Could not emit complete signal."))); closeMono.emitEmpty((signalType, emitResult) -> onEmitSinkFailure(signalType, emitResult, handlerName + ". Error closing mono.")); } } private boolean onEmitSinkFailure(SignalType signalType, Sinks.EmitResult emitResult, String message) { addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult) .log(message); return false; } private synchronized void updateEndpointState(AmqpEndpointState sendLinkState, AmqpEndpointState receiveLinkState) { if (sendLinkState != null) { this.sendLinkState = sendLinkState; } else if (receiveLinkState != null) { this.receiveLinkState = receiveLinkState; } logger.atVerbose() .addKeyValue("sendState", this.sendLinkState) .addKeyValue("receiveState", this.receiveLinkState) .log("Updating endpoint states."); if (this.sendLinkState == this.receiveLinkState) { this.endpointStates.emitNext(this.sendLinkState, Sinks.EmitFailureHandler.FAIL_FAST); } } private void terminateUnconfirmedSends(Throwable error) { logger.verbose("Terminating {} unconfirmed sends (reason: {}).", unconfirmedSends.size(), error.getMessage()); Map.Entry<UnsignedLong, MonoSink<Message>> next; int count = 0; while ((next = unconfirmedSends.pollFirstEntry()) != null) { MonoSink<Message> sink = next.getValue(); recordDelivery(getSinkContext(sink), null); sink.error(error); count++; } logger.atVerbose() .log("completed the termination of {} unconfirmed sends (reason: {}).", count, error.getMessage()); } /** * Captures current time in mono context - used to report send metric */ private Mono<Message> captureStartTime(Message toSend, Mono<Message> publisher) { if (metricsProvider.isRequestResponseDurationEnabled()) { String operationName = "unknown"; if (toSend != null && toSend.getApplicationProperties() != null && toSend.getApplicationProperties().getValue() != null) { Map<String, Object> properties = toSend.getApplicationProperties().getValue(); Object operationObj = properties.get(MANAGEMENT_OPERATION_KEY); if (operationObj instanceof String) { operationName = (String) operationObj; } } return publisher.contextWrite( Context.of(START_SEND_TIME_CONTEXT_KEY, Instant.now()).put(OPERATION_CONTEXT_KEY, operationName)); } return publisher; } @SuppressWarnings("deprecation") private static ContextView getSinkContext(MonoSink<?> sink) { return sink.currentContext(); } /** * Records send call duration metric. **/ private void recordDelivery(ContextView context, Message response) { if (metricsProvider.isRequestResponseDurationEnabled()) { Object startTimestamp = context.getOrDefault(START_SEND_TIME_CONTEXT_KEY, null); Object operationName = context.getOrDefault(OPERATION_CONTEXT_KEY, null); AmqpResponseCode responseCode = response == null ? null : RequestResponseUtils.getStatusCode(response); if (startTimestamp instanceof Instant && operationName instanceof String) { metricsProvider.recordRequestResponseDuration( ((Instant) startTimestamp).toEpochMilli(), (String) operationName, responseCode); } } } }
great catch thanks!
private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(amqpMessage); if (statusCode != AmqpResponseCode.OK) { LOGGER.atWarning() .addKeyValue("statusCode", statusCode) .log("AMQP response did not contain OK status code.", statusCode); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { LOGGER.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { LOGGER.atWarning() .addKeyValue("expectedType", Map.class) .addKeyValue("actualType", responseBodyMap.getClass()) .log("AMQP response body is not correct instance."); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(ManagementConstants.MESSAGES); if (messages == null) { LOGGER.atWarning().addKeyValue("expectedKey", ManagementConstants.MESSAGES) .log("AMQP response body did not contain key."); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { LOGGER.atWarning() .addKeyValue("expectedType", Iterable.class) .addKeyValue("actualType", messages.getClass()) .log("Response body contents is not the correct type."); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { LOGGER.atWarning() .addKeyValue("expectedType", Map.class) .addKeyValue("actualType", message.getClass()) .log("Message inside iterable of message is not correct type."); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(ManagementConstants.MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); if (((Map) message).containsKey(ManagementConstants.LOCK_TOKEN_KEY)) { receivedMessage.setLockToken((UUID) ((Map) message).get(ManagementConstants.LOCK_TOKEN_KEY)); } messageList.add(receivedMessage); } return messageList; }
.log("AMQP response did not contain OK status code.", statusCode);
private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(amqpMessage); if (statusCode != AmqpResponseCode.OK) { LOGGER.atWarning() .addKeyValue("statusCode", statusCode) .log("AMQP response did not contain OK status code."); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { LOGGER.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { LOGGER.atWarning() .addKeyValue("expectedType", Map.class) .addKeyValue("actualType", responseBodyMap.getClass()) .log("AMQP response body is not correct instance."); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(ManagementConstants.MESSAGES); if (messages == null) { LOGGER.atWarning().addKeyValue("expectedKey", ManagementConstants.MESSAGES) .log("AMQP response body did not contain key."); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { LOGGER.atWarning() .addKeyValue("expectedType", Iterable.class) .addKeyValue("actualType", messages.getClass()) .log("Response body contents is not the correct type."); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { LOGGER.atWarning() .addKeyValue("expectedType", Map.class) .addKeyValue("actualType", message.getClass()) .log("Message inside iterable of message is not correct type."); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(ManagementConstants.MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); if (((Map) message).containsKey(ManagementConstants.LOCK_TOKEN_KEY)) { receivedMessage.setLockToken((UUID) ((Map) message).get(ManagementConstants.LOCK_TOKEN_KEY)); } messageList.add(receivedMessage); } return messageList; }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; AmqpMessageBodyType brokeredBodyType = brokeredMessage.getRawAmqpMessage().getBody().getBodyType(); final Message amqpMessage = Proton.message(); byte[] body; if (brokeredBodyType == AmqpMessageBodyType.DATA || brokeredBodyType == null) { body = brokeredMessage.getBody().toBytes(); amqpMessage.setBody(new Data(new Binary(body))); } else if (brokeredBodyType == AmqpMessageBodyType.SEQUENCE) { List<Object> sequenceList = brokeredMessage.getRawAmqpMessage().getBody().getSequence(); amqpMessage.setBody(new AmqpSequence(sequenceList)); } else if (brokeredBodyType == AmqpMessageBodyType.VALUE) { amqpMessage.setBody(new AmqpValue(brokeredMessage.getRawAmqpMessage().getBody().getValue())); } if (brokeredMessage.getApplicationProperties() != null) { Map<String, Object> describedTypeMap = convertToDescribedType(brokeredMessage.getApplicationProperties()); amqpMessage.setApplicationProperties(new ApplicationProperties(describedTypeMap)); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getSubject()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final AmqpMessageProperties brokeredProperties = brokeredMessage.getRawAmqpMessage().getProperties(); amqpMessage.setContentEncoding(brokeredProperties.getContentEncoding()); if (brokeredProperties.getGroupSequence() != null) { amqpMessage.setGroupSequence(brokeredProperties.getGroupSequence()); } amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.getProperties().setUserId(new Binary(brokeredProperties.getUserId())); if (brokeredProperties.getAbsoluteExpiryTime() != null) { amqpMessage.getProperties().setAbsoluteExpiryTime(Date.from(brokeredProperties.getAbsoluteExpiryTime() .toInstant())); } if (brokeredProperties.getCreationTime() != null) { amqpMessage.getProperties().setCreationTime(Date.from(brokeredProperties.getCreationTime().toInstant())); } amqpMessage.setFooter(new Footer(brokeredMessage.getRawAmqpMessage().getFooter())); AmqpMessageHeader header = brokeredMessage.getRawAmqpMessage().getHeader(); if (header.getDeliveryCount() != null) { amqpMessage.setDeliveryCount(header.getDeliveryCount()); } if (header.getPriority() != null) { amqpMessage.setPriority(header.getPriority()); } if (header.isDurable() != null) { amqpMessage.setDurable(header.isDurable()); } if (header.isFirstAcquirer() != null) { amqpMessage.setFirstAcquirer(header.isFirstAcquirer()); } if (header.getTimeToLive() != null) { amqpMessage.setTtl(header.getTimeToLive().toMillis()); } final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()), Date.from(brokeredMessage.getScheduledEnqueueTime().toInstant())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_ANNOTATION_NAME.getValue()), brokeredMessage.getPartitionKey()); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); final Map<Symbol, Object> deliveryAnnotationsMap = new HashMap<>(); final Map<String, Object> deliveryAnnotations = brokeredMessage.getRawAmqpMessage() .getDeliveryAnnotations(); for (Map.Entry<String, Object> deliveryEntry : deliveryAnnotations.entrySet()) { deliveryAnnotationsMap.put(Symbol.valueOf(deliveryEntry.getKey()), deliveryEntry.getValue()); } amqpMessage.setDeliveryAnnotations(new DeliveryAnnotations(deliveryAnnotationsMap)); return amqpMessage; } /** * Convert specific type to described type for sending on the wire. * @param propertiesValue application properties set by user which may contain specific type. * @return Map only contains primitive type and described type. */ private static Map<String, Object> convertToDescribedType(Map<String, Object> propertiesValue) { for (Map.Entry<String, Object> entry : propertiesValue.entrySet()) { Object value = entry.getValue(); if (value instanceof URI) { entry.setValue(new UriDescribedType((URI) value)); } else if (value instanceof OffsetDateTime) { entry.setValue(new OffsetDateTimeDescribedType((OffsetDateTime) value)); } else if (value instanceof Duration) { entry.setValue(new DurationDescribedType((Duration) value)); } } return propertiesValue; } /** * Convert described type to origin type. * @param propertiesValue application properties from amqp message may contain described type. * @return Map without described type. */ private static Map<String, Object> convertToOriginType(Map<String, Object> propertiesValue) { for (Map.Entry<String, Object> entry : propertiesValue.entrySet()) { Object value = entry.getValue(); if (value instanceof DescribedType) { entry.setValue(MessageUtils.describedToOrigin((DescribedType) value)); } } return propertiesValue; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == Long.class) { return (List<T>) deserializeListOfLong(message); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } private List<Long> deserializeListOfLong(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.SEQUENCE_NUMBERS); if (expirationListObj instanceof long[]) { return Arrays.stream((long[]) expirationListObj) .boxed() .collect(Collectors.toList()); } } } return Collections.emptyList(); } private List<OffsetDateTime> deserializeListOfOffsetDateTime(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.EXPIRATIONS); if (expirationListObj instanceof Date[]) { return Arrays.stream((Date[]) expirationListObj) .map(date -> date.toInstant().atOffset(ZoneOffset.UTC)) .collect(Collectors.toList()); } } } return Collections.emptyList(); } @SuppressWarnings("rawtypes") private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final Section body = amqpMessage.getBody(); AmqpMessageBody amqpMessageBody; if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); amqpMessageBody = AmqpMessageBody.fromData(messageData.getArray()); } else if (body instanceof AmqpValue) { amqpMessageBody = AmqpMessageBody.fromValue(((AmqpValue) body).getValue()); } else if (body instanceof AmqpSequence) { @SuppressWarnings("unchecked") List<Object> messageData = ((AmqpSequence) body).getValue(); amqpMessageBody = AmqpMessageBody.fromSequence(messageData); } else { LOGGER.atWarning() .addKeyValue("actualType", body.getType()) .log("Message body is not correct. Not setting body contents."); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } } else { LOGGER.atWarning() .addKeyValue("actualType", "null") .log("Message body is not correct. Not setting body contents."); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } final ServiceBusReceivedMessage brokeredMessage = new ServiceBusReceivedMessage(amqpMessageBody); AmqpAnnotatedMessage brokeredAmqpAnnotatedMessage = brokeredMessage.getRawAmqpMessage(); ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { final Map<String, Object> propertiesValue = convertToOriginType(applicationProperties.getValue()); brokeredAmqpAnnotatedMessage.getApplicationProperties().putAll(propertiesValue); } final AmqpMessageHeader brokeredHeader = brokeredAmqpAnnotatedMessage.getHeader(); brokeredHeader.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredHeader.setDeliveryCount(amqpMessage.getDeliveryCount()); brokeredHeader.setDurable(amqpMessage.getHeader().getDurable()); brokeredHeader.setFirstAcquirer(amqpMessage.getHeader().getFirstAcquirer()); brokeredHeader.setPriority(amqpMessage.getPriority()); final Footer footer = amqpMessage.getFooter(); if (footer != null && footer.getValue() != null) { @SuppressWarnings("unchecked") final Map<Symbol, Object> footerValue = footer.getValue(); setValues(footerValue, brokeredAmqpAnnotatedMessage.getFooter()); } final AmqpMessageProperties brokeredProperties = brokeredAmqpAnnotatedMessage.getProperties(); brokeredProperties.setReplyToGroupId(amqpMessage.getReplyToGroupId()); final String replyTo = amqpMessage.getReplyTo(); if (replyTo != null) { brokeredProperties.setReplyTo(new AmqpAddress(amqpMessage.getReplyTo())); } final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredProperties.setMessageId(new AmqpMessageId(messageId.toString())); } brokeredProperties.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredProperties.setCorrelationId(new AmqpMessageId(correlationId.toString())); } final Properties amqpProperties = amqpMessage.getProperties(); if (amqpProperties != null) { final String to = amqpProperties.getTo(); if (to != null) { brokeredProperties.setTo(new AmqpAddress(amqpProperties.getTo())); } if (amqpProperties.getAbsoluteExpiryTime() != null) { brokeredProperties.setAbsoluteExpiryTime(amqpProperties.getAbsoluteExpiryTime().toInstant() .atOffset(ZoneOffset.UTC)); } if (amqpProperties.getCreationTime() != null) { brokeredProperties.setCreationTime(amqpProperties.getCreationTime().toInstant() .atOffset(ZoneOffset.UTC)); } } brokeredProperties.setSubject(amqpMessage.getSubject()); brokeredProperties.setGroupId(amqpMessage.getGroupId()); brokeredProperties.setContentEncoding(amqpMessage.getContentEncoding()); brokeredProperties.setGroupSequence(amqpMessage.getGroupSequence()); brokeredProperties.setUserId(amqpMessage.getUserId()); final DeliveryAnnotations deliveryAnnotations = amqpMessage.getDeliveryAnnotations(); if (deliveryAnnotations != null) { setValues(deliveryAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getDeliveryAnnotations()); } final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { setValues(messageAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getMessageAnnotations()); } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } private void setValues(Map<Symbol, Object> sourceMap, Map<String, Object> targetMap) { if (sourceMap != null) { for (Map.Entry<Symbol, Object> entry : sourceMap.entrySet()) { targetMap.put(entry.getKey().toString(), entry.getValue()); } } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof ServiceBusDescribedType) { ServiceBusDescribedType describedType = (ServiceBusDescribedType) obj; return describedType.size(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; AmqpMessageBodyType brokeredBodyType = brokeredMessage.getRawAmqpMessage().getBody().getBodyType(); final Message amqpMessage = Proton.message(); byte[] body; if (brokeredBodyType == AmqpMessageBodyType.DATA || brokeredBodyType == null) { body = brokeredMessage.getBody().toBytes(); amqpMessage.setBody(new Data(new Binary(body))); } else if (brokeredBodyType == AmqpMessageBodyType.SEQUENCE) { List<Object> sequenceList = brokeredMessage.getRawAmqpMessage().getBody().getSequence(); amqpMessage.setBody(new AmqpSequence(sequenceList)); } else if (brokeredBodyType == AmqpMessageBodyType.VALUE) { amqpMessage.setBody(new AmqpValue(brokeredMessage.getRawAmqpMessage().getBody().getValue())); } if (brokeredMessage.getApplicationProperties() != null) { Map<String, Object> describedTypeMap = convertToDescribedType(brokeredMessage.getApplicationProperties()); amqpMessage.setApplicationProperties(new ApplicationProperties(describedTypeMap)); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getSubject()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final AmqpMessageProperties brokeredProperties = brokeredMessage.getRawAmqpMessage().getProperties(); amqpMessage.setContentEncoding(brokeredProperties.getContentEncoding()); if (brokeredProperties.getGroupSequence() != null) { amqpMessage.setGroupSequence(brokeredProperties.getGroupSequence()); } amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.getProperties().setUserId(new Binary(brokeredProperties.getUserId())); if (brokeredProperties.getAbsoluteExpiryTime() != null) { amqpMessage.getProperties().setAbsoluteExpiryTime(Date.from(brokeredProperties.getAbsoluteExpiryTime() .toInstant())); } if (brokeredProperties.getCreationTime() != null) { amqpMessage.getProperties().setCreationTime(Date.from(brokeredProperties.getCreationTime().toInstant())); } amqpMessage.setFooter(new Footer(brokeredMessage.getRawAmqpMessage().getFooter())); AmqpMessageHeader header = brokeredMessage.getRawAmqpMessage().getHeader(); if (header.getDeliveryCount() != null) { amqpMessage.setDeliveryCount(header.getDeliveryCount()); } if (header.getPriority() != null) { amqpMessage.setPriority(header.getPriority()); } if (header.isDurable() != null) { amqpMessage.setDurable(header.isDurable()); } if (header.isFirstAcquirer() != null) { amqpMessage.setFirstAcquirer(header.isFirstAcquirer()); } if (header.getTimeToLive() != null) { amqpMessage.setTtl(header.getTimeToLive().toMillis()); } final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()), Date.from(brokeredMessage.getScheduledEnqueueTime().toInstant())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_ANNOTATION_NAME.getValue()), brokeredMessage.getPartitionKey()); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); final Map<Symbol, Object> deliveryAnnotationsMap = new HashMap<>(); final Map<String, Object> deliveryAnnotations = brokeredMessage.getRawAmqpMessage() .getDeliveryAnnotations(); for (Map.Entry<String, Object> deliveryEntry : deliveryAnnotations.entrySet()) { deliveryAnnotationsMap.put(Symbol.valueOf(deliveryEntry.getKey()), deliveryEntry.getValue()); } amqpMessage.setDeliveryAnnotations(new DeliveryAnnotations(deliveryAnnotationsMap)); return amqpMessage; } /** * Convert specific type to described type for sending on the wire. * @param propertiesValue application properties set by user which may contain specific type. * @return Map only contains primitive type and described type. */ private static Map<String, Object> convertToDescribedType(Map<String, Object> propertiesValue) { for (Map.Entry<String, Object> entry : propertiesValue.entrySet()) { Object value = entry.getValue(); if (value instanceof URI) { entry.setValue(new UriDescribedType((URI) value)); } else if (value instanceof OffsetDateTime) { entry.setValue(new OffsetDateTimeDescribedType((OffsetDateTime) value)); } else if (value instanceof Duration) { entry.setValue(new DurationDescribedType((Duration) value)); } } return propertiesValue; } /** * Convert described type to origin type. * @param propertiesValue application properties from amqp message may contain described type. * @return Map without described type. */ private static Map<String, Object> convertToOriginType(Map<String, Object> propertiesValue) { for (Map.Entry<String, Object> entry : propertiesValue.entrySet()) { Object value = entry.getValue(); if (value instanceof DescribedType) { entry.setValue(MessageUtils.describedToOrigin((DescribedType) value)); } } return propertiesValue; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == Long.class) { return (List<T>) deserializeListOfLong(message); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } private List<Long> deserializeListOfLong(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.SEQUENCE_NUMBERS); if (expirationListObj instanceof long[]) { return Arrays.stream((long[]) expirationListObj) .boxed() .collect(Collectors.toList()); } } } return Collections.emptyList(); } private List<OffsetDateTime> deserializeListOfOffsetDateTime(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.EXPIRATIONS); if (expirationListObj instanceof Date[]) { return Arrays.stream((Date[]) expirationListObj) .map(date -> date.toInstant().atOffset(ZoneOffset.UTC)) .collect(Collectors.toList()); } } } return Collections.emptyList(); } @SuppressWarnings("rawtypes") private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final Section body = amqpMessage.getBody(); AmqpMessageBody amqpMessageBody; if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); amqpMessageBody = AmqpMessageBody.fromData(messageData.getArray()); } else if (body instanceof AmqpValue) { amqpMessageBody = AmqpMessageBody.fromValue(((AmqpValue) body).getValue()); } else if (body instanceof AmqpSequence) { @SuppressWarnings("unchecked") List<Object> messageData = ((AmqpSequence) body).getValue(); amqpMessageBody = AmqpMessageBody.fromSequence(messageData); } else { LOGGER.atWarning() .addKeyValue("actualType", body.getType()) .log("Message body is not correct. Not setting body contents."); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } } else { LOGGER.atWarning() .addKeyValue("actualType", "null") .log("Message body is not correct. Not setting body contents."); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } final ServiceBusReceivedMessage brokeredMessage = new ServiceBusReceivedMessage(amqpMessageBody); AmqpAnnotatedMessage brokeredAmqpAnnotatedMessage = brokeredMessage.getRawAmqpMessage(); ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { final Map<String, Object> propertiesValue = convertToOriginType(applicationProperties.getValue()); brokeredAmqpAnnotatedMessage.getApplicationProperties().putAll(propertiesValue); } final AmqpMessageHeader brokeredHeader = brokeredAmqpAnnotatedMessage.getHeader(); brokeredHeader.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredHeader.setDeliveryCount(amqpMessage.getDeliveryCount()); brokeredHeader.setDurable(amqpMessage.getHeader().getDurable()); brokeredHeader.setFirstAcquirer(amqpMessage.getHeader().getFirstAcquirer()); brokeredHeader.setPriority(amqpMessage.getPriority()); final Footer footer = amqpMessage.getFooter(); if (footer != null && footer.getValue() != null) { @SuppressWarnings("unchecked") final Map<Symbol, Object> footerValue = footer.getValue(); setValues(footerValue, brokeredAmqpAnnotatedMessage.getFooter()); } final AmqpMessageProperties brokeredProperties = brokeredAmqpAnnotatedMessage.getProperties(); brokeredProperties.setReplyToGroupId(amqpMessage.getReplyToGroupId()); final String replyTo = amqpMessage.getReplyTo(); if (replyTo != null) { brokeredProperties.setReplyTo(new AmqpAddress(amqpMessage.getReplyTo())); } final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredProperties.setMessageId(new AmqpMessageId(messageId.toString())); } brokeredProperties.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredProperties.setCorrelationId(new AmqpMessageId(correlationId.toString())); } final Properties amqpProperties = amqpMessage.getProperties(); if (amqpProperties != null) { final String to = amqpProperties.getTo(); if (to != null) { brokeredProperties.setTo(new AmqpAddress(amqpProperties.getTo())); } if (amqpProperties.getAbsoluteExpiryTime() != null) { brokeredProperties.setAbsoluteExpiryTime(amqpProperties.getAbsoluteExpiryTime().toInstant() .atOffset(ZoneOffset.UTC)); } if (amqpProperties.getCreationTime() != null) { brokeredProperties.setCreationTime(amqpProperties.getCreationTime().toInstant() .atOffset(ZoneOffset.UTC)); } } brokeredProperties.setSubject(amqpMessage.getSubject()); brokeredProperties.setGroupId(amqpMessage.getGroupId()); brokeredProperties.setContentEncoding(amqpMessage.getContentEncoding()); brokeredProperties.setGroupSequence(amqpMessage.getGroupSequence()); brokeredProperties.setUserId(amqpMessage.getUserId()); final DeliveryAnnotations deliveryAnnotations = amqpMessage.getDeliveryAnnotations(); if (deliveryAnnotations != null) { setValues(deliveryAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getDeliveryAnnotations()); } final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { setValues(messageAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getMessageAnnotations()); } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } private void setValues(Map<Symbol, Object> sourceMap, Map<String, Object> targetMap) { if (sourceMap != null) { for (Map.Entry<Symbol, Object> entry : sourceMap.entrySet()) { targetMap.put(entry.getKey().toString(), entry.getValue()); } } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof ServiceBusDescribedType) { ServiceBusDescribedType describedType = (ServiceBusDescribedType) obj; return describedType.size(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
By default, the Java AST parsing library will generate annotations with attributes `Deprecated()`, if you want just `Deprecated` you should use `.addAnnotation(new MarkerAnnotationExpr("Deprecated"))`
public void customizeResourceEvents(LibraryCustomization customization, Logger logger) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); Arrays.asList("Action", "Delete", "Write").forEach(action -> { Arrays.asList("Cancel", "Failure", "Success").forEach(result -> { String className = String.format("Resource%s%sEventData", action, result); ClassCustomization classCustomization = packageModels.getClass(className); classCustomization.customizeAst(compilationUnit -> { ClassOrInterfaceDeclaration classDec = compilationUnit.getClassByName(className).get(); compilationUnit.addImport("com.azure.core.util.logging.ClientLogger"); compilationUnit.addImport("com.azure.core.util.serializer.JacksonAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerEncoding"); compilationUnit.addImport("java.io.IOException"); compilationUnit.addImport("java.io.UncheckedIOException"); classDec.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(" + className + ".class)"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); classDec.addFieldWithInitializer("SerializerAdapter", "DEFAULT_SERIALIZER_ADAPTER", parseExpression("JacksonAdapter.createDefaultSerializerAdapter()"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); Arrays.asList("Authorization", "Claims", "HttpRequest").forEach(method -> { classDec.getMethodsByName("get" + method).get(0).setName("getResource" + method); classDec.getMethodsByName("set" + method).get(0).setName("setResource" + method); }); classDec.addMethod("getClaims", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ final Map<String, String> resourceClaims = getResourceClaims(); if (!resourceClaims.isEmpty()) { try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceClaims, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } return null; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the claims property: The properties of the claims.")))) .addBlockTag("return", "the claims value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setClaims", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "claims") .setBody(parseBlock("{ try { setResourceClaims(DEFAULT_SERIALIZER_ADAPTER.deserialize(claims, Map.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the claims property: The properties of the claims.")))) .addBlockTag("param", "claims the claims value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("getHttpRequest", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ ResourceHttpRequest resourceHttpRequest = getResourceHttpRequest(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceHttpRequest, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the httpRequest property: The details of the operation.")))) .addBlockTag("return", "the httpRequest value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setHttpRequest", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "httpRequest") .setBody(parseBlock("{ try { setResourceHttpRequest( DEFAULT_SERIALIZER_ADAPTER.deserialize(httpRequest, ResourceHttpRequest.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the httpRequest property: The details of the operation.")))) .addBlockTag("param", "httpRequest the httpRequest value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("getAuthorization", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ final ResourceAuthorization resourceAuthorization = getResourceAuthorization(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceAuthorization, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the authorization property: The requested authorization for the operation.")))) .addBlockTag("return", "the authorization value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setAuthorization", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "authorization") .setBody(parseBlock("{ try { setResourceAuthorization( DEFAULT_SERIALIZER_ADAPTER.deserialize(authorization, ResourceAuthorization.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the authorization property: The requested authorization for the operation.")))) .addBlockTag("param", "authorization the authorization value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); }); }); }); }
.addAnnotation("Deprecated")
public void customizeResourceEvents(LibraryCustomization customization, Logger logger) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); Arrays.asList("Action", "Delete", "Write").forEach(action -> { Arrays.asList("Cancel", "Failure", "Success").forEach(result -> { String className = String.format("Resource%s%sEventData", action, result); ClassCustomization classCustomization = packageModels.getClass(className); classCustomization.customizeAst(compilationUnit -> { ClassOrInterfaceDeclaration clazz = compilationUnit.getClassByName(className).get(); compilationUnit.addImport("com.azure.core.util.logging.ClientLogger"); compilationUnit.addImport("com.azure.core.util.serializer.JacksonAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerEncoding"); compilationUnit.addImport("java.io.IOException"); compilationUnit.addImport("java.io.UncheckedIOException"); clazz.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(" + className + ".class)"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); clazz.addFieldWithInitializer("SerializerAdapter", "DEFAULT_SERIALIZER_ADAPTER", parseExpression("JacksonAdapter.createDefaultSerializerAdapter()"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); Arrays.asList("Authorization", "Claims", "HttpRequest").forEach(method -> { clazz.getMethodsByName("get" + method).forEach(methodDeclaration -> { methodDeclaration.setName("getResource" + method); }); clazz.getMethodsByName("set" + method).forEach(methodDeclaration -> { methodDeclaration.setName("setResource" + method); }); }); clazz.addMethod("getClaims", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ final Map<String, String> resourceClaims = getResourceClaims(); if (!resourceClaims.isEmpty()) { try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceClaims, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } return null; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the claims property: The properties of the claims.")))) .addBlockTag("return", "the claims value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setClaims", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "claims") .setBody(parseBlock("{ try { setResourceClaims(DEFAULT_SERIALIZER_ADAPTER.deserialize(claims, Map.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the claims property: The properties of the claims.")))) .addBlockTag("param", "claims the claims value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("getHttpRequest", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ ResourceHttpRequest resourceHttpRequest = getResourceHttpRequest(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceHttpRequest, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the httpRequest property: The details of the operation.")))) .addBlockTag("return", "the httpRequest value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setHttpRequest", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "httpRequest") .setBody(parseBlock("{ try { setResourceHttpRequest( DEFAULT_SERIALIZER_ADAPTER.deserialize(httpRequest, ResourceHttpRequest.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the httpRequest property: The details of the operation.")))) .addBlockTag("param", "httpRequest the httpRequest value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("getAuthorization", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ final ResourceAuthorization resourceAuthorization = getResourceAuthorization(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceAuthorization, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the authorization property: The requested authorization for the operation.")))) .addBlockTag("return", "the authorization value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setAuthorization", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "authorization") .setBody(parseBlock("{ try { setResourceAuthorization( DEFAULT_SERIALIZER_ADAPTER.deserialize(authorization, ResourceAuthorization.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the authorization property: The requested authorization for the operation.")))) .addBlockTag("param", "authorization the authorization value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); }); }); }); }
class SystemEventNames {" + System.lineSeparator(); private static final String PRIVATE_CTOR = "/**" + System.lineSeparator() + " * Get a mapping of all the system event type strings to their respective class. This is used by default in" + System.lineSeparator() + " * the {@link EventGridEvent} and {@link CloudEvent} classes." + System.lineSeparator() + " * @return a mapping of all the system event strings to system event objects." + System.lineSeparator() + " */" + System.lineSeparator() + " public static Map<String, Class<?>> getSystemEventMappings() {" + System.lineSeparator() + " return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS);" + System.lineSeparator() + " }" + System.lineSeparator() + System.lineSeparator() + " private SystemEventNames() { " + System.lineSeparator() + " }"; @Override public void customize(LibraryCustomization customization, Logger logger) { List<ClassCustomization> classCustomizations = customization.getPackage("com.azure.messaging.eventgrid.systemevents") .listClasses(); StringBuilder sb = new StringBuilder(); List<String> imports = new ArrayList<>(); Map<String, String> nameMap = new TreeMap<>(); Map<String, String> classMap = new TreeMap<>(); Map<String, String> descriptionMap = new TreeMap<>(); Map<String, String> constantNameMap = new TreeMap<>(); logger.info("Total number of classes " + classCustomizations.size()); List<ClassCustomization> eventData = classCustomizations .stream() .filter(classCustomization -> classCustomization.getClassName().endsWith("EventData")) .collect(Collectors.toList()); List<String> validEventDescription = eventData.stream() .filter(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().lastIndexOf(" event."); boolean hasEventName = startIndex > 0 && endIndex > 0; if (!hasEventName) { logger.info("Class " + classCustomization.getClassName() + " " + classCustomization.getJavadoc().getDescription()); } return hasEventName; }) .map(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().indexOf(" ", startIndex); String eventName = classCustomization.getJavadoc().getDescription().substring(startIndex, endIndex); String className = classCustomization.getClassName(); String constantName = getReplacementName(getConstantName(className.replace("EventData", ""))); constantNameMap.put(className, constantName); nameMap.put(className, eventName); classMap.put(className, className + ".class"); descriptionMap.put(className, classCustomization.getJavadoc().getDescription()); imports.add(className); return eventName; }) .collect(Collectors.toList()); Collections.sort(imports); sb.append(SYSTEM_EVENT_CLASS_HEADER); sb.append("import com.azure.core.models.CloudEvent;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.EventGridEvent;"); sb.append(System.lineSeparator()); sb.append("import java.util.Collections;"); sb.append(System.lineSeparator()); sb.append("import java.util.HashMap;"); sb.append(System.lineSeparator()); sb.append("import java.util.Map;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberAddedToThreadWithUserEventData;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberRemovedFromThreadWithUserEventData;"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("import com.azure.messaging.eventgrid.systemevents." + className + ";"); sb.append(System.lineSeparator()); } sb.append(CLASS_DEF); for (String className : imports) { sb.append("/**"); sb.append(System.lineSeparator()); sb.append("* " + descriptionMap.get(className)); sb.append(System.lineSeparator()); sb.append("*/"); sb.append(System.lineSeparator()); sb.append("public static final String " + constantNameMap.get(className) + " = \"" + nameMap.get(className) + "\";"); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); } sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberAddedToThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatThreadParticipantRemoved\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("private static final Map<String, Class<?>> SYSTEM_EVENT_MAPPINGS = new HashMap<String, Class<?>>()" + " {{"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("put(" + constantNameMap.get(className) + ", " + classMap.get(className) + ");"); sb.append(System.lineSeparator()); } sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD, AcsChatParticipantRemovedFromThreadEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER, AcsChatParticipantRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER, AcsChatMemberAddedToThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER, AcsChatMemberRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("}};"); sb.append(System.lineSeparator()); sb.append(PRIVATE_CTOR); sb.append("}"); sb.append(System.lineSeparator()); logger.info("Total number of events " + eventData.size()); logger.info("Total number of events with proper description " + validEventDescription.size()); customization.getRawEditor() .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); customizeMediaJobOutputAsset(customization); customizeStorageDirectoryDeletedEventData(customization); customizeAcsRecordingFileStatusUpdatedEventDataDuration(customization); customizeMediaLiveEventChannelArchiveHeartbeatEventDataDuration(customization); customizeMediaLiveEventIngestHeartbeatEventData(customization); customizeResourceEvents(customization, logger); customizeEventGridClientImplImports(customization); }
class SystemEventNames {" + System.lineSeparator(); private static final String PRIVATE_CTOR = "/**" + System.lineSeparator() + " * Get a mapping of all the system event type strings to their respective class. This is used by default in" + System.lineSeparator() + " * the {@link EventGridEvent} and {@link CloudEvent} classes." + System.lineSeparator() + " * @return a mapping of all the system event strings to system event objects." + System.lineSeparator() + " */" + System.lineSeparator() + " public static Map<String, Class<?>> getSystemEventMappings() {" + System.lineSeparator() + " return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS);" + System.lineSeparator() + " }" + System.lineSeparator() + System.lineSeparator() + " private SystemEventNames() { " + System.lineSeparator() + " }"; @Override public void customize(LibraryCustomization customization, Logger logger) { List<ClassCustomization> classCustomizations = customization.getPackage("com.azure.messaging.eventgrid.systemevents") .listClasses(); StringBuilder sb = new StringBuilder(); List<String> imports = new ArrayList<>(); Map<String, String> nameMap = new TreeMap<>(); Map<String, String> classMap = new TreeMap<>(); Map<String, String> descriptionMap = new TreeMap<>(); Map<String, String> constantNameMap = new TreeMap<>(); logger.info("Total number of classes " + classCustomizations.size()); List<ClassCustomization> eventData = classCustomizations .stream() .filter(classCustomization -> classCustomization.getClassName().endsWith("EventData")) .collect(Collectors.toList()); List<String> validEventDescription = eventData.stream() .filter(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().lastIndexOf(" event."); boolean hasEventName = startIndex > 0 && endIndex > 0; if (!hasEventName) { logger.info("Class " + classCustomization.getClassName() + " " + classCustomization.getJavadoc().getDescription()); } return hasEventName; }) .map(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().indexOf(" ", startIndex); String eventName = classCustomization.getJavadoc().getDescription().substring(startIndex, endIndex); String className = classCustomization.getClassName(); String constantName = getReplacementName(getConstantName(className.replace("EventData", ""))); constantNameMap.put(className, constantName); nameMap.put(className, eventName); classMap.put(className, className + ".class"); descriptionMap.put(className, classCustomization.getJavadoc().getDescription()); imports.add(className); return eventName; }) .collect(Collectors.toList()); Collections.sort(imports); sb.append(SYSTEM_EVENT_CLASS_HEADER); sb.append("import com.azure.core.models.CloudEvent;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.EventGridEvent;"); sb.append(System.lineSeparator()); sb.append("import java.util.Collections;"); sb.append(System.lineSeparator()); sb.append("import java.util.HashMap;"); sb.append(System.lineSeparator()); sb.append("import java.util.Map;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberAddedToThreadWithUserEventData;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberRemovedFromThreadWithUserEventData;"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("import com.azure.messaging.eventgrid.systemevents." + className + ";"); sb.append(System.lineSeparator()); } sb.append(CLASS_DEF); for (String className : imports) { sb.append("/**"); sb.append(System.lineSeparator()); sb.append("* " + descriptionMap.get(className)); sb.append(System.lineSeparator()); sb.append("*/"); sb.append(System.lineSeparator()); sb.append("public static final String " + constantNameMap.get(className) + " = \"" + nameMap.get(className) + "\";"); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); } sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberAddedToThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatThreadParticipantRemoved\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("private static final Map<String, Class<?>> SYSTEM_EVENT_MAPPINGS = new HashMap<String, Class<?>>()" + " {{"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("put(" + constantNameMap.get(className) + ", " + classMap.get(className) + ");"); sb.append(System.lineSeparator()); } sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD, AcsChatParticipantRemovedFromThreadEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER, AcsChatParticipantRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER, AcsChatMemberAddedToThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER, AcsChatMemberRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("}};"); sb.append(System.lineSeparator()); sb.append(PRIVATE_CTOR); sb.append("}"); sb.append(System.lineSeparator()); logger.info("Total number of events " + eventData.size()); logger.info("Total number of events with proper description " + validEventDescription.size()); customization.getRawEditor() .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); customizeMediaJobOutputAsset(customization); customizeStorageDirectoryDeletedEventData(customization); customizeAcsRecordingFileStatusUpdatedEventDataDuration(customization); customizeMediaLiveEventChannelArchiveHeartbeatEventDataDuration(customization); customizeMediaLiveEventIngestHeartbeatEventData(customization); customizeResourceEvents(customization, logger); customizeEventGridClientImplImports(customization); }
May want to use a slightly safer design like ```java classDec.getMethodByName("get" + method).ifPresent(getter -> getter.setName("getResource" + method)); classDec.getMethodByName("set" + method).ifPresent(setter -> setter.setName("setResource" + method)); ```
public void customizeResourceEvents(LibraryCustomization customization, Logger logger) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); Arrays.asList("Action", "Delete", "Write").forEach(action -> { Arrays.asList("Cancel", "Failure", "Success").forEach(result -> { String className = String.format("Resource%s%sEventData", action, result); ClassCustomization classCustomization = packageModels.getClass(className); classCustomization.customizeAst(compilationUnit -> { ClassOrInterfaceDeclaration classDec = compilationUnit.getClassByName(className).get(); compilationUnit.addImport("com.azure.core.util.logging.ClientLogger"); compilationUnit.addImport("com.azure.core.util.serializer.JacksonAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerEncoding"); compilationUnit.addImport("java.io.IOException"); compilationUnit.addImport("java.io.UncheckedIOException"); classDec.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(" + className + ".class)"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); classDec.addFieldWithInitializer("SerializerAdapter", "DEFAULT_SERIALIZER_ADAPTER", parseExpression("JacksonAdapter.createDefaultSerializerAdapter()"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); Arrays.asList("Authorization", "Claims", "HttpRequest").forEach(method -> { classDec.getMethodsByName("get" + method).get(0).setName("getResource" + method); classDec.getMethodsByName("set" + method).get(0).setName("setResource" + method); }); classDec.addMethod("getClaims", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ final Map<String, String> resourceClaims = getResourceClaims(); if (!resourceClaims.isEmpty()) { try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceClaims, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } return null; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the claims property: The properties of the claims.")))) .addBlockTag("return", "the claims value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setClaims", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "claims") .setBody(parseBlock("{ try { setResourceClaims(DEFAULT_SERIALIZER_ADAPTER.deserialize(claims, Map.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the claims property: The properties of the claims.")))) .addBlockTag("param", "claims the claims value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("getHttpRequest", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ ResourceHttpRequest resourceHttpRequest = getResourceHttpRequest(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceHttpRequest, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the httpRequest property: The details of the operation.")))) .addBlockTag("return", "the httpRequest value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setHttpRequest", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "httpRequest") .setBody(parseBlock("{ try { setResourceHttpRequest( DEFAULT_SERIALIZER_ADAPTER.deserialize(httpRequest, ResourceHttpRequest.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the httpRequest property: The details of the operation.")))) .addBlockTag("param", "httpRequest the httpRequest value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("getAuthorization", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ final ResourceAuthorization resourceAuthorization = getResourceAuthorization(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceAuthorization, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the authorization property: The requested authorization for the operation.")))) .addBlockTag("return", "the authorization value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setAuthorization", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "authorization") .setBody(parseBlock("{ try { setResourceAuthorization( DEFAULT_SERIALIZER_ADAPTER.deserialize(authorization, ResourceAuthorization.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the authorization property: The requested authorization for the operation.")))) .addBlockTag("param", "authorization the authorization value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); }); }); }); }
classDec.getMethodsByName("set" + method).get(0).setName("setResource" + method);
public void customizeResourceEvents(LibraryCustomization customization, Logger logger) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); Arrays.asList("Action", "Delete", "Write").forEach(action -> { Arrays.asList("Cancel", "Failure", "Success").forEach(result -> { String className = String.format("Resource%s%sEventData", action, result); ClassCustomization classCustomization = packageModels.getClass(className); classCustomization.customizeAst(compilationUnit -> { ClassOrInterfaceDeclaration clazz = compilationUnit.getClassByName(className).get(); compilationUnit.addImport("com.azure.core.util.logging.ClientLogger"); compilationUnit.addImport("com.azure.core.util.serializer.JacksonAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerEncoding"); compilationUnit.addImport("java.io.IOException"); compilationUnit.addImport("java.io.UncheckedIOException"); clazz.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(" + className + ".class)"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); clazz.addFieldWithInitializer("SerializerAdapter", "DEFAULT_SERIALIZER_ADAPTER", parseExpression("JacksonAdapter.createDefaultSerializerAdapter()"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); Arrays.asList("Authorization", "Claims", "HttpRequest").forEach(method -> { clazz.getMethodsByName("get" + method).forEach(methodDeclaration -> { methodDeclaration.setName("getResource" + method); }); clazz.getMethodsByName("set" + method).forEach(methodDeclaration -> { methodDeclaration.setName("setResource" + method); }); }); clazz.addMethod("getClaims", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ final Map<String, String> resourceClaims = getResourceClaims(); if (!resourceClaims.isEmpty()) { try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceClaims, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } return null; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the claims property: The properties of the claims.")))) .addBlockTag("return", "the claims value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setClaims", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "claims") .setBody(parseBlock("{ try { setResourceClaims(DEFAULT_SERIALIZER_ADAPTER.deserialize(claims, Map.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the claims property: The properties of the claims.")))) .addBlockTag("param", "claims the claims value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("getHttpRequest", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ ResourceHttpRequest resourceHttpRequest = getResourceHttpRequest(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceHttpRequest, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the httpRequest property: The details of the operation.")))) .addBlockTag("return", "the httpRequest value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setHttpRequest", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "httpRequest") .setBody(parseBlock("{ try { setResourceHttpRequest( DEFAULT_SERIALIZER_ADAPTER.deserialize(httpRequest, ResourceHttpRequest.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the httpRequest property: The details of the operation.")))) .addBlockTag("param", "httpRequest the httpRequest value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("getAuthorization", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ final ResourceAuthorization resourceAuthorization = getResourceAuthorization(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceAuthorization, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the authorization property: The requested authorization for the operation.")))) .addBlockTag("return", "the authorization value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setAuthorization", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "authorization") .setBody(parseBlock("{ try { setResourceAuthorization( DEFAULT_SERIALIZER_ADAPTER.deserialize(authorization, ResourceAuthorization.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the authorization property: The requested authorization for the operation.")))) .addBlockTag("param", "authorization the authorization value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); }); }); }); }
class SystemEventNames {" + System.lineSeparator(); private static final String PRIVATE_CTOR = "/**" + System.lineSeparator() + " * Get a mapping of all the system event type strings to their respective class. This is used by default in" + System.lineSeparator() + " * the {@link EventGridEvent} and {@link CloudEvent} classes." + System.lineSeparator() + " * @return a mapping of all the system event strings to system event objects." + System.lineSeparator() + " */" + System.lineSeparator() + " public static Map<String, Class<?>> getSystemEventMappings() {" + System.lineSeparator() + " return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS);" + System.lineSeparator() + " }" + System.lineSeparator() + System.lineSeparator() + " private SystemEventNames() { " + System.lineSeparator() + " }"; @Override public void customize(LibraryCustomization customization, Logger logger) { List<ClassCustomization> classCustomizations = customization.getPackage("com.azure.messaging.eventgrid.systemevents") .listClasses(); StringBuilder sb = new StringBuilder(); List<String> imports = new ArrayList<>(); Map<String, String> nameMap = new TreeMap<>(); Map<String, String> classMap = new TreeMap<>(); Map<String, String> descriptionMap = new TreeMap<>(); Map<String, String> constantNameMap = new TreeMap<>(); logger.info("Total number of classes " + classCustomizations.size()); List<ClassCustomization> eventData = classCustomizations .stream() .filter(classCustomization -> classCustomization.getClassName().endsWith("EventData")) .collect(Collectors.toList()); List<String> validEventDescription = eventData.stream() .filter(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().lastIndexOf(" event."); boolean hasEventName = startIndex > 0 && endIndex > 0; if (!hasEventName) { logger.info("Class " + classCustomization.getClassName() + " " + classCustomization.getJavadoc().getDescription()); } return hasEventName; }) .map(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().indexOf(" ", startIndex); String eventName = classCustomization.getJavadoc().getDescription().substring(startIndex, endIndex); String className = classCustomization.getClassName(); String constantName = getReplacementName(getConstantName(className.replace("EventData", ""))); constantNameMap.put(className, constantName); nameMap.put(className, eventName); classMap.put(className, className + ".class"); descriptionMap.put(className, classCustomization.getJavadoc().getDescription()); imports.add(className); return eventName; }) .collect(Collectors.toList()); Collections.sort(imports); sb.append(SYSTEM_EVENT_CLASS_HEADER); sb.append("import com.azure.core.models.CloudEvent;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.EventGridEvent;"); sb.append(System.lineSeparator()); sb.append("import java.util.Collections;"); sb.append(System.lineSeparator()); sb.append("import java.util.HashMap;"); sb.append(System.lineSeparator()); sb.append("import java.util.Map;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberAddedToThreadWithUserEventData;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberRemovedFromThreadWithUserEventData;"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("import com.azure.messaging.eventgrid.systemevents." + className + ";"); sb.append(System.lineSeparator()); } sb.append(CLASS_DEF); for (String className : imports) { sb.append("/**"); sb.append(System.lineSeparator()); sb.append("* " + descriptionMap.get(className)); sb.append(System.lineSeparator()); sb.append("*/"); sb.append(System.lineSeparator()); sb.append("public static final String " + constantNameMap.get(className) + " = \"" + nameMap.get(className) + "\";"); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); } sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberAddedToThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatThreadParticipantRemoved\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("private static final Map<String, Class<?>> SYSTEM_EVENT_MAPPINGS = new HashMap<String, Class<?>>()" + " {{"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("put(" + constantNameMap.get(className) + ", " + classMap.get(className) + ");"); sb.append(System.lineSeparator()); } sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD, AcsChatParticipantRemovedFromThreadEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER, AcsChatParticipantRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER, AcsChatMemberAddedToThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER, AcsChatMemberRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("}};"); sb.append(System.lineSeparator()); sb.append(PRIVATE_CTOR); sb.append("}"); sb.append(System.lineSeparator()); logger.info("Total number of events " + eventData.size()); logger.info("Total number of events with proper description " + validEventDescription.size()); customization.getRawEditor() .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); customizeMediaJobOutputAsset(customization); customizeStorageDirectoryDeletedEventData(customization); customizeAcsRecordingFileStatusUpdatedEventDataDuration(customization); customizeMediaLiveEventChannelArchiveHeartbeatEventDataDuration(customization); customizeMediaLiveEventIngestHeartbeatEventData(customization); customizeResourceEvents(customization, logger); customizeEventGridClientImplImports(customization); }
class SystemEventNames {" + System.lineSeparator(); private static final String PRIVATE_CTOR = "/**" + System.lineSeparator() + " * Get a mapping of all the system event type strings to their respective class. This is used by default in" + System.lineSeparator() + " * the {@link EventGridEvent} and {@link CloudEvent} classes." + System.lineSeparator() + " * @return a mapping of all the system event strings to system event objects." + System.lineSeparator() + " */" + System.lineSeparator() + " public static Map<String, Class<?>> getSystemEventMappings() {" + System.lineSeparator() + " return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS);" + System.lineSeparator() + " }" + System.lineSeparator() + System.lineSeparator() + " private SystemEventNames() { " + System.lineSeparator() + " }"; @Override public void customize(LibraryCustomization customization, Logger logger) { List<ClassCustomization> classCustomizations = customization.getPackage("com.azure.messaging.eventgrid.systemevents") .listClasses(); StringBuilder sb = new StringBuilder(); List<String> imports = new ArrayList<>(); Map<String, String> nameMap = new TreeMap<>(); Map<String, String> classMap = new TreeMap<>(); Map<String, String> descriptionMap = new TreeMap<>(); Map<String, String> constantNameMap = new TreeMap<>(); logger.info("Total number of classes " + classCustomizations.size()); List<ClassCustomization> eventData = classCustomizations .stream() .filter(classCustomization -> classCustomization.getClassName().endsWith("EventData")) .collect(Collectors.toList()); List<String> validEventDescription = eventData.stream() .filter(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().lastIndexOf(" event."); boolean hasEventName = startIndex > 0 && endIndex > 0; if (!hasEventName) { logger.info("Class " + classCustomization.getClassName() + " " + classCustomization.getJavadoc().getDescription()); } return hasEventName; }) .map(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().indexOf(" ", startIndex); String eventName = classCustomization.getJavadoc().getDescription().substring(startIndex, endIndex); String className = classCustomization.getClassName(); String constantName = getReplacementName(getConstantName(className.replace("EventData", ""))); constantNameMap.put(className, constantName); nameMap.put(className, eventName); classMap.put(className, className + ".class"); descriptionMap.put(className, classCustomization.getJavadoc().getDescription()); imports.add(className); return eventName; }) .collect(Collectors.toList()); Collections.sort(imports); sb.append(SYSTEM_EVENT_CLASS_HEADER); sb.append("import com.azure.core.models.CloudEvent;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.EventGridEvent;"); sb.append(System.lineSeparator()); sb.append("import java.util.Collections;"); sb.append(System.lineSeparator()); sb.append("import java.util.HashMap;"); sb.append(System.lineSeparator()); sb.append("import java.util.Map;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberAddedToThreadWithUserEventData;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberRemovedFromThreadWithUserEventData;"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("import com.azure.messaging.eventgrid.systemevents." + className + ";"); sb.append(System.lineSeparator()); } sb.append(CLASS_DEF); for (String className : imports) { sb.append("/**"); sb.append(System.lineSeparator()); sb.append("* " + descriptionMap.get(className)); sb.append(System.lineSeparator()); sb.append("*/"); sb.append(System.lineSeparator()); sb.append("public static final String " + constantNameMap.get(className) + " = \"" + nameMap.get(className) + "\";"); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); } sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberAddedToThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatThreadParticipantRemoved\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("private static final Map<String, Class<?>> SYSTEM_EVENT_MAPPINGS = new HashMap<String, Class<?>>()" + " {{"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("put(" + constantNameMap.get(className) + ", " + classMap.get(className) + ");"); sb.append(System.lineSeparator()); } sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD, AcsChatParticipantRemovedFromThreadEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER, AcsChatParticipantRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER, AcsChatMemberAddedToThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER, AcsChatMemberRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("}};"); sb.append(System.lineSeparator()); sb.append(PRIVATE_CTOR); sb.append("}"); sb.append(System.lineSeparator()); logger.info("Total number of events " + eventData.size()); logger.info("Total number of events with proper description " + validEventDescription.size()); customization.getRawEditor() .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); customizeMediaJobOutputAsset(customization); customizeStorageDirectoryDeletedEventData(customization); customizeAcsRecordingFileStatusUpdatedEventDataDuration(customization); customizeMediaLiveEventChannelArchiveHeartbeatEventDataDuration(customization); customizeMediaLiveEventIngestHeartbeatEventData(customization); customizeResourceEvents(customization, logger); customizeEventGridClientImplImports(customization); }
There is no `getMethodByName` in `classDec`. This returns a list and we should ensure all methods contained in that list get renamed as we may add overloads. So, this should be more like: `classDec.getMethodsByName("oldName").forEach(methodDeclaration -> methodDeclaration.setName("newName")`
public void customizeResourceEvents(LibraryCustomization customization, Logger logger) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); Arrays.asList("Action", "Delete", "Write").forEach(action -> { Arrays.asList("Cancel", "Failure", "Success").forEach(result -> { String className = String.format("Resource%s%sEventData", action, result); ClassCustomization classCustomization = packageModels.getClass(className); classCustomization.customizeAst(compilationUnit -> { ClassOrInterfaceDeclaration classDec = compilationUnit.getClassByName(className).get(); compilationUnit.addImport("com.azure.core.util.logging.ClientLogger"); compilationUnit.addImport("com.azure.core.util.serializer.JacksonAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerEncoding"); compilationUnit.addImport("java.io.IOException"); compilationUnit.addImport("java.io.UncheckedIOException"); classDec.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(" + className + ".class)"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); classDec.addFieldWithInitializer("SerializerAdapter", "DEFAULT_SERIALIZER_ADAPTER", parseExpression("JacksonAdapter.createDefaultSerializerAdapter()"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); Arrays.asList("Authorization", "Claims", "HttpRequest").forEach(method -> { classDec.getMethodsByName("get" + method).get(0).setName("getResource" + method); classDec.getMethodsByName("set" + method).get(0).setName("setResource" + method); }); classDec.addMethod("getClaims", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ final Map<String, String> resourceClaims = getResourceClaims(); if (!resourceClaims.isEmpty()) { try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceClaims, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } return null; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the claims property: The properties of the claims.")))) .addBlockTag("return", "the claims value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setClaims", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "claims") .setBody(parseBlock("{ try { setResourceClaims(DEFAULT_SERIALIZER_ADAPTER.deserialize(claims, Map.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the claims property: The properties of the claims.")))) .addBlockTag("param", "claims the claims value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("getHttpRequest", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ ResourceHttpRequest resourceHttpRequest = getResourceHttpRequest(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceHttpRequest, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the httpRequest property: The details of the operation.")))) .addBlockTag("return", "the httpRequest value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setHttpRequest", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "httpRequest") .setBody(parseBlock("{ try { setResourceHttpRequest( DEFAULT_SERIALIZER_ADAPTER.deserialize(httpRequest, ResourceHttpRequest.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the httpRequest property: The details of the operation.")))) .addBlockTag("param", "httpRequest the httpRequest value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("getAuthorization", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ final ResourceAuthorization resourceAuthorization = getResourceAuthorization(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceAuthorization, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the authorization property: The requested authorization for the operation.")))) .addBlockTag("return", "the authorization value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setAuthorization", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "authorization") .setBody(parseBlock("{ try { setResourceAuthorization( DEFAULT_SERIALIZER_ADAPTER.deserialize(authorization, ResourceAuthorization.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the authorization property: The requested authorization for the operation.")))) .addBlockTag("param", "authorization the authorization value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); }); }); }); }
classDec.getMethodsByName("set" + method).get(0).setName("setResource" + method);
public void customizeResourceEvents(LibraryCustomization customization, Logger logger) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); Arrays.asList("Action", "Delete", "Write").forEach(action -> { Arrays.asList("Cancel", "Failure", "Success").forEach(result -> { String className = String.format("Resource%s%sEventData", action, result); ClassCustomization classCustomization = packageModels.getClass(className); classCustomization.customizeAst(compilationUnit -> { ClassOrInterfaceDeclaration clazz = compilationUnit.getClassByName(className).get(); compilationUnit.addImport("com.azure.core.util.logging.ClientLogger"); compilationUnit.addImport("com.azure.core.util.serializer.JacksonAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerEncoding"); compilationUnit.addImport("java.io.IOException"); compilationUnit.addImport("java.io.UncheckedIOException"); clazz.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(" + className + ".class)"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); clazz.addFieldWithInitializer("SerializerAdapter", "DEFAULT_SERIALIZER_ADAPTER", parseExpression("JacksonAdapter.createDefaultSerializerAdapter()"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); Arrays.asList("Authorization", "Claims", "HttpRequest").forEach(method -> { clazz.getMethodsByName("get" + method).forEach(methodDeclaration -> { methodDeclaration.setName("getResource" + method); }); clazz.getMethodsByName("set" + method).forEach(methodDeclaration -> { methodDeclaration.setName("setResource" + method); }); }); clazz.addMethod("getClaims", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ final Map<String, String> resourceClaims = getResourceClaims(); if (!resourceClaims.isEmpty()) { try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceClaims, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } return null; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the claims property: The properties of the claims.")))) .addBlockTag("return", "the claims value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setClaims", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "claims") .setBody(parseBlock("{ try { setResourceClaims(DEFAULT_SERIALIZER_ADAPTER.deserialize(claims, Map.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the claims property: The properties of the claims.")))) .addBlockTag("param", "claims the claims value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("getHttpRequest", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ ResourceHttpRequest resourceHttpRequest = getResourceHttpRequest(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceHttpRequest, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the httpRequest property: The details of the operation.")))) .addBlockTag("return", "the httpRequest value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setHttpRequest", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "httpRequest") .setBody(parseBlock("{ try { setResourceHttpRequest( DEFAULT_SERIALIZER_ADAPTER.deserialize(httpRequest, ResourceHttpRequest.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the httpRequest property: The details of the operation.")))) .addBlockTag("param", "httpRequest the httpRequest value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("getAuthorization", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ final ResourceAuthorization resourceAuthorization = getResourceAuthorization(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceAuthorization, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the authorization property: The requested authorization for the operation.")))) .addBlockTag("return", "the authorization value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setAuthorization", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "authorization") .setBody(parseBlock("{ try { setResourceAuthorization( DEFAULT_SERIALIZER_ADAPTER.deserialize(authorization, ResourceAuthorization.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the authorization property: The requested authorization for the operation.")))) .addBlockTag("param", "authorization the authorization value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); }); }); }); }
class SystemEventNames {" + System.lineSeparator(); private static final String PRIVATE_CTOR = "/**" + System.lineSeparator() + " * Get a mapping of all the system event type strings to their respective class. This is used by default in" + System.lineSeparator() + " * the {@link EventGridEvent} and {@link CloudEvent} classes." + System.lineSeparator() + " * @return a mapping of all the system event strings to system event objects." + System.lineSeparator() + " */" + System.lineSeparator() + " public static Map<String, Class<?>> getSystemEventMappings() {" + System.lineSeparator() + " return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS);" + System.lineSeparator() + " }" + System.lineSeparator() + System.lineSeparator() + " private SystemEventNames() { " + System.lineSeparator() + " }"; @Override public void customize(LibraryCustomization customization, Logger logger) { List<ClassCustomization> classCustomizations = customization.getPackage("com.azure.messaging.eventgrid.systemevents") .listClasses(); StringBuilder sb = new StringBuilder(); List<String> imports = new ArrayList<>(); Map<String, String> nameMap = new TreeMap<>(); Map<String, String> classMap = new TreeMap<>(); Map<String, String> descriptionMap = new TreeMap<>(); Map<String, String> constantNameMap = new TreeMap<>(); logger.info("Total number of classes " + classCustomizations.size()); List<ClassCustomization> eventData = classCustomizations .stream() .filter(classCustomization -> classCustomization.getClassName().endsWith("EventData")) .collect(Collectors.toList()); List<String> validEventDescription = eventData.stream() .filter(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().lastIndexOf(" event."); boolean hasEventName = startIndex > 0 && endIndex > 0; if (!hasEventName) { logger.info("Class " + classCustomization.getClassName() + " " + classCustomization.getJavadoc().getDescription()); } return hasEventName; }) .map(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().indexOf(" ", startIndex); String eventName = classCustomization.getJavadoc().getDescription().substring(startIndex, endIndex); String className = classCustomization.getClassName(); String constantName = getReplacementName(getConstantName(className.replace("EventData", ""))); constantNameMap.put(className, constantName); nameMap.put(className, eventName); classMap.put(className, className + ".class"); descriptionMap.put(className, classCustomization.getJavadoc().getDescription()); imports.add(className); return eventName; }) .collect(Collectors.toList()); Collections.sort(imports); sb.append(SYSTEM_EVENT_CLASS_HEADER); sb.append("import com.azure.core.models.CloudEvent;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.EventGridEvent;"); sb.append(System.lineSeparator()); sb.append("import java.util.Collections;"); sb.append(System.lineSeparator()); sb.append("import java.util.HashMap;"); sb.append(System.lineSeparator()); sb.append("import java.util.Map;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberAddedToThreadWithUserEventData;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberRemovedFromThreadWithUserEventData;"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("import com.azure.messaging.eventgrid.systemevents." + className + ";"); sb.append(System.lineSeparator()); } sb.append(CLASS_DEF); for (String className : imports) { sb.append("/**"); sb.append(System.lineSeparator()); sb.append("* " + descriptionMap.get(className)); sb.append(System.lineSeparator()); sb.append("*/"); sb.append(System.lineSeparator()); sb.append("public static final String " + constantNameMap.get(className) + " = \"" + nameMap.get(className) + "\";"); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); } sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberAddedToThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatThreadParticipantRemoved\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("private static final Map<String, Class<?>> SYSTEM_EVENT_MAPPINGS = new HashMap<String, Class<?>>()" + " {{"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("put(" + constantNameMap.get(className) + ", " + classMap.get(className) + ");"); sb.append(System.lineSeparator()); } sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD, AcsChatParticipantRemovedFromThreadEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER, AcsChatParticipantRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER, AcsChatMemberAddedToThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER, AcsChatMemberRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("}};"); sb.append(System.lineSeparator()); sb.append(PRIVATE_CTOR); sb.append("}"); sb.append(System.lineSeparator()); logger.info("Total number of events " + eventData.size()); logger.info("Total number of events with proper description " + validEventDescription.size()); customization.getRawEditor() .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); customizeMediaJobOutputAsset(customization); customizeStorageDirectoryDeletedEventData(customization); customizeAcsRecordingFileStatusUpdatedEventDataDuration(customization); customizeMediaLiveEventChannelArchiveHeartbeatEventDataDuration(customization); customizeMediaLiveEventIngestHeartbeatEventData(customization); customizeResourceEvents(customization, logger); customizeEventGridClientImplImports(customization); }
class SystemEventNames {" + System.lineSeparator(); private static final String PRIVATE_CTOR = "/**" + System.lineSeparator() + " * Get a mapping of all the system event type strings to their respective class. This is used by default in" + System.lineSeparator() + " * the {@link EventGridEvent} and {@link CloudEvent} classes." + System.lineSeparator() + " * @return a mapping of all the system event strings to system event objects." + System.lineSeparator() + " */" + System.lineSeparator() + " public static Map<String, Class<?>> getSystemEventMappings() {" + System.lineSeparator() + " return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS);" + System.lineSeparator() + " }" + System.lineSeparator() + System.lineSeparator() + " private SystemEventNames() { " + System.lineSeparator() + " }"; @Override public void customize(LibraryCustomization customization, Logger logger) { List<ClassCustomization> classCustomizations = customization.getPackage("com.azure.messaging.eventgrid.systemevents") .listClasses(); StringBuilder sb = new StringBuilder(); List<String> imports = new ArrayList<>(); Map<String, String> nameMap = new TreeMap<>(); Map<String, String> classMap = new TreeMap<>(); Map<String, String> descriptionMap = new TreeMap<>(); Map<String, String> constantNameMap = new TreeMap<>(); logger.info("Total number of classes " + classCustomizations.size()); List<ClassCustomization> eventData = classCustomizations .stream() .filter(classCustomization -> classCustomization.getClassName().endsWith("EventData")) .collect(Collectors.toList()); List<String> validEventDescription = eventData.stream() .filter(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().lastIndexOf(" event."); boolean hasEventName = startIndex > 0 && endIndex > 0; if (!hasEventName) { logger.info("Class " + classCustomization.getClassName() + " " + classCustomization.getJavadoc().getDescription()); } return hasEventName; }) .map(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().indexOf(" ", startIndex); String eventName = classCustomization.getJavadoc().getDescription().substring(startIndex, endIndex); String className = classCustomization.getClassName(); String constantName = getReplacementName(getConstantName(className.replace("EventData", ""))); constantNameMap.put(className, constantName); nameMap.put(className, eventName); classMap.put(className, className + ".class"); descriptionMap.put(className, classCustomization.getJavadoc().getDescription()); imports.add(className); return eventName; }) .collect(Collectors.toList()); Collections.sort(imports); sb.append(SYSTEM_EVENT_CLASS_HEADER); sb.append("import com.azure.core.models.CloudEvent;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.EventGridEvent;"); sb.append(System.lineSeparator()); sb.append("import java.util.Collections;"); sb.append(System.lineSeparator()); sb.append("import java.util.HashMap;"); sb.append(System.lineSeparator()); sb.append("import java.util.Map;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberAddedToThreadWithUserEventData;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberRemovedFromThreadWithUserEventData;"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("import com.azure.messaging.eventgrid.systemevents." + className + ";"); sb.append(System.lineSeparator()); } sb.append(CLASS_DEF); for (String className : imports) { sb.append("/**"); sb.append(System.lineSeparator()); sb.append("* " + descriptionMap.get(className)); sb.append(System.lineSeparator()); sb.append("*/"); sb.append(System.lineSeparator()); sb.append("public static final String " + constantNameMap.get(className) + " = \"" + nameMap.get(className) + "\";"); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); } sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberAddedToThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatThreadParticipantRemoved\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("private static final Map<String, Class<?>> SYSTEM_EVENT_MAPPINGS = new HashMap<String, Class<?>>()" + " {{"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("put(" + constantNameMap.get(className) + ", " + classMap.get(className) + ");"); sb.append(System.lineSeparator()); } sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD, AcsChatParticipantRemovedFromThreadEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER, AcsChatParticipantRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER, AcsChatMemberAddedToThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER, AcsChatMemberRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("}};"); sb.append(System.lineSeparator()); sb.append(PRIVATE_CTOR); sb.append("}"); sb.append(System.lineSeparator()); logger.info("Total number of events " + eventData.size()); logger.info("Total number of events with proper description " + validEventDescription.size()); customization.getRawEditor() .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); customizeMediaJobOutputAsset(customization); customizeStorageDirectoryDeletedEventData(customization); customizeAcsRecordingFileStatusUpdatedEventDataDuration(customization); customizeMediaLiveEventChannelArchiveHeartbeatEventDataDuration(customization); customizeMediaLiveEventIngestHeartbeatEventData(customization); customizeResourceEvents(customization, logger); customizeEventGridClientImplImports(customization); }
done! good call.
public void customizeResourceEvents(LibraryCustomization customization, Logger logger) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); Arrays.asList("Action", "Delete", "Write").forEach(action -> { Arrays.asList("Cancel", "Failure", "Success").forEach(result -> { String className = String.format("Resource%s%sEventData", action, result); ClassCustomization classCustomization = packageModels.getClass(className); classCustomization.customizeAst(compilationUnit -> { ClassOrInterfaceDeclaration classDec = compilationUnit.getClassByName(className).get(); compilationUnit.addImport("com.azure.core.util.logging.ClientLogger"); compilationUnit.addImport("com.azure.core.util.serializer.JacksonAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerEncoding"); compilationUnit.addImport("java.io.IOException"); compilationUnit.addImport("java.io.UncheckedIOException"); classDec.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(" + className + ".class)"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); classDec.addFieldWithInitializer("SerializerAdapter", "DEFAULT_SERIALIZER_ADAPTER", parseExpression("JacksonAdapter.createDefaultSerializerAdapter()"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); Arrays.asList("Authorization", "Claims", "HttpRequest").forEach(method -> { classDec.getMethodsByName("get" + method).get(0).setName("getResource" + method); classDec.getMethodsByName("set" + method).get(0).setName("setResource" + method); }); classDec.addMethod("getClaims", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ final Map<String, String> resourceClaims = getResourceClaims(); if (!resourceClaims.isEmpty()) { try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceClaims, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } return null; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the claims property: The properties of the claims.")))) .addBlockTag("return", "the claims value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setClaims", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "claims") .setBody(parseBlock("{ try { setResourceClaims(DEFAULT_SERIALIZER_ADAPTER.deserialize(claims, Map.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the claims property: The properties of the claims.")))) .addBlockTag("param", "claims the claims value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("getHttpRequest", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ ResourceHttpRequest resourceHttpRequest = getResourceHttpRequest(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceHttpRequest, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the httpRequest property: The details of the operation.")))) .addBlockTag("return", "the httpRequest value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setHttpRequest", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "httpRequest") .setBody(parseBlock("{ try { setResourceHttpRequest( DEFAULT_SERIALIZER_ADAPTER.deserialize(httpRequest, ResourceHttpRequest.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the httpRequest property: The details of the operation.")))) .addBlockTag("param", "httpRequest the httpRequest value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("getAuthorization", Keyword.PUBLIC) .setType("String") .addAnnotation("Deprecated") .setBody(parseBlock("{ final ResourceAuthorization resourceAuthorization = getResourceAuthorization(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceAuthorization, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the authorization property: The requested authorization for the operation.")))) .addBlockTag("return", "the authorization value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); classDec.addMethod("setAuthorization", Keyword.PUBLIC) .setType(className) .addAnnotation("Deprecated") .addParameter("String", "authorization") .setBody(parseBlock("{ try { setResourceAuthorization( DEFAULT_SERIALIZER_ADAPTER.deserialize(authorization, ResourceAuthorization.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the authorization property: The requested authorization for the operation.")))) .addBlockTag("param", "authorization the authorization value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); }); }); }); }
classDec.getMethodsByName("set" + method).get(0).setName("setResource" + method);
public void customizeResourceEvents(LibraryCustomization customization, Logger logger) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); Arrays.asList("Action", "Delete", "Write").forEach(action -> { Arrays.asList("Cancel", "Failure", "Success").forEach(result -> { String className = String.format("Resource%s%sEventData", action, result); ClassCustomization classCustomization = packageModels.getClass(className); classCustomization.customizeAst(compilationUnit -> { ClassOrInterfaceDeclaration clazz = compilationUnit.getClassByName(className).get(); compilationUnit.addImport("com.azure.core.util.logging.ClientLogger"); compilationUnit.addImport("com.azure.core.util.serializer.JacksonAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerAdapter"); compilationUnit.addImport("com.azure.core.util.serializer.SerializerEncoding"); compilationUnit.addImport("java.io.IOException"); compilationUnit.addImport("java.io.UncheckedIOException"); clazz.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(" + className + ".class)"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); clazz.addFieldWithInitializer("SerializerAdapter", "DEFAULT_SERIALIZER_ADAPTER", parseExpression("JacksonAdapter.createDefaultSerializerAdapter()"), Keyword.STATIC, Keyword.FINAL, Keyword.PRIVATE); Arrays.asList("Authorization", "Claims", "HttpRequest").forEach(method -> { clazz.getMethodsByName("get" + method).forEach(methodDeclaration -> { methodDeclaration.setName("getResource" + method); }); clazz.getMethodsByName("set" + method).forEach(methodDeclaration -> { methodDeclaration.setName("setResource" + method); }); }); clazz.addMethod("getClaims", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ final Map<String, String> resourceClaims = getResourceClaims(); if (!resourceClaims.isEmpty()) { try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceClaims, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } return null; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the claims property: The properties of the claims.")))) .addBlockTag("return", "the claims value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setClaims", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "claims") .setBody(parseBlock("{ try { setResourceClaims(DEFAULT_SERIALIZER_ADAPTER.deserialize(claims, Map.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the claims property: The properties of the claims.")))) .addBlockTag("param", "claims the claims value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("getHttpRequest", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ ResourceHttpRequest resourceHttpRequest = getResourceHttpRequest(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceHttpRequest, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the httpRequest property: The details of the operation.")))) .addBlockTag("return", "the httpRequest value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setHttpRequest", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "httpRequest") .setBody(parseBlock("{ try { setResourceHttpRequest( DEFAULT_SERIALIZER_ADAPTER.deserialize(httpRequest, ResourceHttpRequest.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the httpRequest property: The details of the operation.")))) .addBlockTag("param", "httpRequest the httpRequest value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("getAuthorization", Keyword.PUBLIC) .setType("String") .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .setBody(parseBlock("{ final ResourceAuthorization resourceAuthorization = getResourceAuthorization(); try { return DEFAULT_SERIALIZER_ADAPTER.serialize(resourceAuthorization, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the authorization property: The requested authorization for the operation.")))) .addBlockTag("return", "the authorization value.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); clazz.addMethod("setAuthorization", Keyword.PUBLIC) .setType(className) .addAnnotation(new MarkerAnnotationExpr("Deprecated")) .addParameter("String", "authorization") .setBody(parseBlock("{ try { setResourceAuthorization( DEFAULT_SERIALIZER_ADAPTER.deserialize(authorization, ResourceAuthorization.class, SerializerEncoding.JSON)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return this; }")) .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the authorization property: The requested authorization for the operation.")))) .addBlockTag("param", "authorization the authorization value to set.") .addBlockTag("return", "the " + className + " object itself.") .addBlockTag("deprecated", "This method is no longer supported since v4.9.0. <p> Use {@link " + className + " ); }); }); }); }
class SystemEventNames {" + System.lineSeparator(); private static final String PRIVATE_CTOR = "/**" + System.lineSeparator() + " * Get a mapping of all the system event type strings to their respective class. This is used by default in" + System.lineSeparator() + " * the {@link EventGridEvent} and {@link CloudEvent} classes." + System.lineSeparator() + " * @return a mapping of all the system event strings to system event objects." + System.lineSeparator() + " */" + System.lineSeparator() + " public static Map<String, Class<?>> getSystemEventMappings() {" + System.lineSeparator() + " return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS);" + System.lineSeparator() + " }" + System.lineSeparator() + System.lineSeparator() + " private SystemEventNames() { " + System.lineSeparator() + " }"; @Override public void customize(LibraryCustomization customization, Logger logger) { List<ClassCustomization> classCustomizations = customization.getPackage("com.azure.messaging.eventgrid.systemevents") .listClasses(); StringBuilder sb = new StringBuilder(); List<String> imports = new ArrayList<>(); Map<String, String> nameMap = new TreeMap<>(); Map<String, String> classMap = new TreeMap<>(); Map<String, String> descriptionMap = new TreeMap<>(); Map<String, String> constantNameMap = new TreeMap<>(); logger.info("Total number of classes " + classCustomizations.size()); List<ClassCustomization> eventData = classCustomizations .stream() .filter(classCustomization -> classCustomization.getClassName().endsWith("EventData")) .collect(Collectors.toList()); List<String> validEventDescription = eventData.stream() .filter(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().lastIndexOf(" event."); boolean hasEventName = startIndex > 0 && endIndex > 0; if (!hasEventName) { logger.info("Class " + classCustomization.getClassName() + " " + classCustomization.getJavadoc().getDescription()); } return hasEventName; }) .map(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().indexOf(" ", startIndex); String eventName = classCustomization.getJavadoc().getDescription().substring(startIndex, endIndex); String className = classCustomization.getClassName(); String constantName = getReplacementName(getConstantName(className.replace("EventData", ""))); constantNameMap.put(className, constantName); nameMap.put(className, eventName); classMap.put(className, className + ".class"); descriptionMap.put(className, classCustomization.getJavadoc().getDescription()); imports.add(className); return eventName; }) .collect(Collectors.toList()); Collections.sort(imports); sb.append(SYSTEM_EVENT_CLASS_HEADER); sb.append("import com.azure.core.models.CloudEvent;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.EventGridEvent;"); sb.append(System.lineSeparator()); sb.append("import java.util.Collections;"); sb.append(System.lineSeparator()); sb.append("import java.util.HashMap;"); sb.append(System.lineSeparator()); sb.append("import java.util.Map;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberAddedToThreadWithUserEventData;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberRemovedFromThreadWithUserEventData;"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("import com.azure.messaging.eventgrid.systemevents." + className + ";"); sb.append(System.lineSeparator()); } sb.append(CLASS_DEF); for (String className : imports) { sb.append("/**"); sb.append(System.lineSeparator()); sb.append("* " + descriptionMap.get(className)); sb.append(System.lineSeparator()); sb.append("*/"); sb.append(System.lineSeparator()); sb.append("public static final String " + constantNameMap.get(className) + " = \"" + nameMap.get(className) + "\";"); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); } sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberAddedToThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatThreadParticipantRemoved\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("private static final Map<String, Class<?>> SYSTEM_EVENT_MAPPINGS = new HashMap<String, Class<?>>()" + " {{"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("put(" + constantNameMap.get(className) + ", " + classMap.get(className) + ");"); sb.append(System.lineSeparator()); } sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD, AcsChatParticipantRemovedFromThreadEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER, AcsChatParticipantRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER, AcsChatMemberAddedToThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER, AcsChatMemberRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("}};"); sb.append(System.lineSeparator()); sb.append(PRIVATE_CTOR); sb.append("}"); sb.append(System.lineSeparator()); logger.info("Total number of events " + eventData.size()); logger.info("Total number of events with proper description " + validEventDescription.size()); customization.getRawEditor() .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); customizeMediaJobOutputAsset(customization); customizeStorageDirectoryDeletedEventData(customization); customizeAcsRecordingFileStatusUpdatedEventDataDuration(customization); customizeMediaLiveEventChannelArchiveHeartbeatEventDataDuration(customization); customizeMediaLiveEventIngestHeartbeatEventData(customization); customizeResourceEvents(customization, logger); customizeEventGridClientImplImports(customization); }
class SystemEventNames {" + System.lineSeparator(); private static final String PRIVATE_CTOR = "/**" + System.lineSeparator() + " * Get a mapping of all the system event type strings to their respective class. This is used by default in" + System.lineSeparator() + " * the {@link EventGridEvent} and {@link CloudEvent} classes." + System.lineSeparator() + " * @return a mapping of all the system event strings to system event objects." + System.lineSeparator() + " */" + System.lineSeparator() + " public static Map<String, Class<?>> getSystemEventMappings() {" + System.lineSeparator() + " return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS);" + System.lineSeparator() + " }" + System.lineSeparator() + System.lineSeparator() + " private SystemEventNames() { " + System.lineSeparator() + " }"; @Override public void customize(LibraryCustomization customization, Logger logger) { List<ClassCustomization> classCustomizations = customization.getPackage("com.azure.messaging.eventgrid.systemevents") .listClasses(); StringBuilder sb = new StringBuilder(); List<String> imports = new ArrayList<>(); Map<String, String> nameMap = new TreeMap<>(); Map<String, String> classMap = new TreeMap<>(); Map<String, String> descriptionMap = new TreeMap<>(); Map<String, String> constantNameMap = new TreeMap<>(); logger.info("Total number of classes " + classCustomizations.size()); List<ClassCustomization> eventData = classCustomizations .stream() .filter(classCustomization -> classCustomization.getClassName().endsWith("EventData")) .collect(Collectors.toList()); List<String> validEventDescription = eventData.stream() .filter(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().lastIndexOf(" event."); boolean hasEventName = startIndex > 0 && endIndex > 0; if (!hasEventName) { logger.info("Class " + classCustomization.getClassName() + " " + classCustomization.getJavadoc().getDescription()); } return hasEventName; }) .map(classCustomization -> { int startIndex = classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); int endIndex = classCustomization.getJavadoc().getDescription().indexOf(" ", startIndex); String eventName = classCustomization.getJavadoc().getDescription().substring(startIndex, endIndex); String className = classCustomization.getClassName(); String constantName = getReplacementName(getConstantName(className.replace("EventData", ""))); constantNameMap.put(className, constantName); nameMap.put(className, eventName); classMap.put(className, className + ".class"); descriptionMap.put(className, classCustomization.getJavadoc().getDescription()); imports.add(className); return eventName; }) .collect(Collectors.toList()); Collections.sort(imports); sb.append(SYSTEM_EVENT_CLASS_HEADER); sb.append("import com.azure.core.models.CloudEvent;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.EventGridEvent;"); sb.append(System.lineSeparator()); sb.append("import java.util.Collections;"); sb.append(System.lineSeparator()); sb.append("import java.util.HashMap;"); sb.append(System.lineSeparator()); sb.append("import java.util.Map;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberAddedToThreadWithUserEventData;"); sb.append(System.lineSeparator()); sb.append("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberRemovedFromThreadWithUserEventData;"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("import com.azure.messaging.eventgrid.systemevents." + className + ";"); sb.append(System.lineSeparator()); } sb.append(CLASS_DEF); for (String className : imports) { sb.append("/**"); sb.append(System.lineSeparator()); sb.append("* " + descriptionMap.get(className)); sb.append(System.lineSeparator()); sb.append("*/"); sb.append(System.lineSeparator()); sb.append("public static final String " + constantNameMap.get(className) + " = \"" + nameMap.get(className) + "\";"); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); } sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberAddedToThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated This event does not exist."); sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatThreadParticipantRemoved\";"); sb.append(System.lineSeparator()); sb.append("/**"); sb.append(System.lineSeparator()); sb.append(" * @deprecated As of 4.1.0, replaced by {@link sb.append(System.lineSeparator()); sb.append(" */"); sb.append(System.lineSeparator()); sb.append("@Deprecated"); sb.append(System.lineSeparator()); sb.append("public static final String COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER ="); sb.append(System.lineSeparator()); sb.append("\"Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser\";"); sb.append(System.lineSeparator()); sb.append("private static final Map<String, Class<?>> SYSTEM_EVENT_MAPPINGS = new HashMap<String, Class<?>>()" + " {{"); sb.append(System.lineSeparator()); for (String className : imports) { sb.append("put(" + constantNameMap.get(className) + ", " + classMap.get(className) + ");"); sb.append(System.lineSeparator()); } sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD, AcsChatParticipantRemovedFromThreadEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MESSAGE_REMOVED_FROM_THREAD_WITH_USER, AcsChatParticipantRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER, AcsChatMemberAddedToThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("put(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER, AcsChatMemberRemovedFromThreadWithUserEventData.class);"); sb.append(System.lineSeparator()); sb.append("}};"); sb.append(System.lineSeparator()); sb.append(PRIVATE_CTOR); sb.append("}"); sb.append(System.lineSeparator()); logger.info("Total number of events " + eventData.size()); logger.info("Total number of events with proper description " + validEventDescription.size()); customization.getRawEditor() .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); customizeMediaJobOutputAsset(customization); customizeStorageDirectoryDeletedEventData(customization); customizeAcsRecordingFileStatusUpdatedEventDataDuration(customization); customizeMediaLiveEventChannelArchiveHeartbeatEventDataDuration(customization); customizeMediaLiveEventIngestHeartbeatEventData(customization); customizeResourceEvents(customization, logger); customizeEventGridClientImplImports(customization); }
1. could you add a comment here mentioning why we're doing the redirection 2. could you include a test case in the PR for the scenario
AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError( new IllegalStateException( "A Safe Working directory could not be" + " found to execute Azure Developer CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; }
builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE));
AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError( new IllegalStateException( "A Safe Working directory could not be" + " found to execute Azure Developer CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(options.getClientOptions(), httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); if (options.getClientOptions() != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); options.getClientOptions().getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(options.getClientOptions(), httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); if (options.getClientOptions() != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); options.getClientOptions().getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } }
We don't need to recompile the pattern each time build*Client is called. This can be made static final.
private String modifyUserAgentString(String applicationId, Configuration userAgentConfiguration) { Pattern pattern = Pattern.compile(USER_AGENT_MODIFICATION_REGEX); String userAgent = UserAgentUtil.toUserAgentString(applicationId, BLOB_CLIENT_NAME, BLOB_CLIENT_VERSION, userAgentConfiguration); Matcher matcher = pattern.matcher(userAgent); String version = encryptionVersion == EncryptionVersion.V2 ? "2.0" : "1.0"; String stringToAppend = "azstorage-clientsideencryption/" + version; if (matcher.matches()) { String segment1 = matcher.group(1) == null ? "" : matcher.group(1); String segment2 = matcher.group(2) == null ? "" : matcher.group(2); String segment3 = matcher.group(3) == null ? "" : matcher.group(3); userAgent = segment1 + stringToAppend + " " + segment2 + segment3; } return userAgent; }
Pattern pattern = Pattern.compile(USER_AGENT_MODIFICATION_REGEX);
private String modifyUserAgentString(String applicationId, Configuration userAgentConfiguration) { Pattern pattern = Pattern.compile(USER_AGENT_MODIFICATION_REGEX); String userAgent = UserAgentUtil.toUserAgentString(applicationId, BLOB_CLIENT_NAME, BLOB_CLIENT_VERSION, userAgentConfiguration); Matcher matcher = pattern.matcher(userAgent); String version = encryptionVersion == EncryptionVersion.V2 ? "2.0" : "1.0"; String stringToAppend = "azstorage-clientsideencryption/" + version; if (matcher.matches() && !userAgent.contains(stringToAppend)) { String segment1 = matcher.group(1) == null ? "" : matcher.group(1); String segment2 = matcher.group(2) == null ? "" : matcher.group(2); String segment3 = matcher.group(3) == null ? "" : matcher.group(3); userAgent = segment1 + stringToAppend + " " + segment2 + segment3; } return userAgent; }
class EncryptedBlobClientBuilder implements TokenCredentialTrait<EncryptedBlobClientBuilder>, ConnectionStringTrait<EncryptedBlobClientBuilder>, AzureNamedKeyCredentialTrait<EncryptedBlobClientBuilder>, AzureSasCredentialTrait<EncryptedBlobClientBuilder>, HttpTrait<EncryptedBlobClientBuilder>, ConfigurationTrait<EncryptedBlobClientBuilder>, EndpointTrait<EncryptedBlobClientBuilder> { private static final ClientLogger LOGGER = new ClientLogger(EncryptedBlobClientBuilder.class); private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-storage-blob-cryptography.properties"); private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String CLIENT_NAME = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String BLOB_CLIENT_NAME = USER_AGENT_PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String BLOB_CLIENT_VERSION = USER_AGENT_PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String USER_AGENT_MODIFICATION_REGEX = "(.*? )?(azsdk-java-azure-storage-blob/12\\.\\d{1,2}\\.\\d{1,2}(?:-beta\\.\\d{1,2})?)( .*?)?"; private String endpoint; private String accountName; private String containerName; private String blobName; private String snapshot; private String versionId; private boolean requiresEncryption; private final EncryptionVersion encryptionVersion; private StorageSharedKeyCredential storageSharedKeyCredential; private TokenCredential tokenCredential; private AzureSasCredential azureSasCredential; private String sasToken; private HttpClient httpClient; private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private HttpLogOptions logOptions; private RequestRetryOptions retryOptions; private RetryOptions coreRetryOptions; private HttpPipeline httpPipeline; private ClientOptions clientOptions = new ClientOptions(); private Configuration configuration; private AsyncKeyEncryptionKey keyWrapper; private AsyncKeyEncryptionKeyResolver keyResolver; private String keyWrapAlgorithm; private BlobServiceVersion version; private CpkInfo customerProvidedKey; private EncryptionScope encryptionScope; /** * Creates a new instance of the EncryptedBlobClientBuilder * @deprecated Use {@link EncryptedBlobClientBuilder */ @Deprecated public EncryptedBlobClientBuilder() { logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = EncryptionVersion.V1; LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } /** * Creates a new instance of the EncryptedBlobClientbuilder. * * @param version The version of the client side encryption protocol to use. It is highly recommended that v2 be * preferred for security reasons, though v1 continues to be supported for compatibility reasons. Note that even a * client configured to encrypt using v2 can decrypt blobs that use the v1 protocol. */ public EncryptedBlobClientBuilder(EncryptionVersion version) { Objects.requireNonNull(version); logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = version; if (EncryptionVersion.V1.equals(this.encryptionVersion)) { LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } } /** * Creates a {@link EncryptedBlobClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * <pre> * EncryptedBlobAsyncClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobAsyncClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * * @return a {@link EncryptedBlobClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobClient buildEncryptedBlobClient() { return new EncryptedBlobClient(buildEncryptedBlobAsyncClient()); } /** * Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * <pre> * EncryptedBlobClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * * @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); checkValidEncryptionParameters(); /* Implicit and explicit root container access are functionally equivalent, but explicit references are easier to read and debug. */ if (CoreUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } BlobServiceVersion serviceVersion = version != null ? version : BlobServiceVersion.getLatest(); return new EncryptedBlobAsyncClient(addBlobUserAgentModificationPolicy(getHttpPipeline()), endpoint, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey, encryptionScope, keyWrapper, keyWrapAlgorithm, versionId, encryptionVersion, requiresEncryption); } private HttpPipeline addBlobUserAgentModificationPolicy(HttpPipeline pipeline) { List<HttpPipelinePolicy> policies = new ArrayList<>(); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = pipeline.getPolicy(i); policies.add(currPolicy); if (currPolicy instanceof UserAgentPolicy) { policies.add(new BlobUserAgentModificationPolicy(CLIENT_NAME, CLIENT_VERSION)); } } return new HttpPipelineBuilder() .httpClient(pipeline.getHttpClient()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .tracer(pipeline.getTracer()) .build(); } private HttpPipeline getHttpPipeline() { CredentialValidator.validateSingleCredentialIsPresent( storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, LOGGER); if (httpPipeline != null) { List<HttpPipelinePolicy> policies = new ArrayList<>(); boolean decryptionPolicyPresent = false; for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = httpPipeline.getPolicy(i); if (currPolicy instanceof BlobDecryptionPolicy) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The passed pipeline was already" + " configured for encryption/decryption in a way that might conflict with the passed key " + "information. Please ensure that the passed pipeline is not already configured for " + "encryption/decryption")); } policies.add(currPolicy); } policies.add(0, new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); return new HttpPipelineBuilder() .httpClient(httpPipeline.getHttpClient()) .tracer(httpPipeline.getTracer()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } Configuration userAgentConfiguration = (configuration == null) ? Configuration.NONE : configuration; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); String applicationId = clientOptions.getApplicationId() != null ? clientOptions.getApplicationId() : logOptions.getApplicationId(); String modifiedUserAgent = modifyUserAgentString(applicationId, userAgentConfiguration); policies.add(new UserAgentPolicy(modifiedUserAgent)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(BuilderUtils.createRetryPolicy(retryOptions, coreRetryOptions, LOGGER)); policies.add(new AddDatePolicy()); HttpHeaders headers = new HttpHeaders(); clientOptions.getHeaders().forEach(header -> headers.put(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new MetadataValidationPolicy()); if (storageSharedKeyCredential != null) { policies.add(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)); } else if (tokenCredential != null) { BuilderHelper.httpsValidation(tokenCredential, "bearer token", endpoint, LOGGER); policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, Constants.STORAGE_SCOPE)); } else if (azureSasCredential != null) { policies.add(new AzureSasCredentialPolicy(azureSasCredential, false)); } else if (sasToken != null) { policies.add(new AzureSasCredentialPolicy(new AzureSasCredential(sasToken), false)); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new ResponseValidationPolicyBuilder() .addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID) .addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256) .build()); policies.add(new HttpLoggingPolicy(logOptions)); policies.add(new ScrubEtagPolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(createTracer(clientOptions)) .build(); } /** * Sets the encryption key parameters for the client * * @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key * @param keyWrapAlgorithm The {@link String} used to wrap the key. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) { this.keyWrapper = key; this.keyWrapAlgorithm = keyWrapAlgorithm; return this; } /** * Sets the encryption parameters for this client * * @param keyResolver The key resolver used to select the correct key for decrypting existing blobs. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) { this.keyResolver = keyResolver; return this; } private void checkValidEncryptionParameters() { if (this.keyWrapper == null && this.keyResolver == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null")); } if (this.keyWrapper != null && this.keyWrapAlgorithm == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Key Wrap Algorithm must be specified with a Key.")); } } /** * Sets the {@link StorageSharedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link StorageSharedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ public EncryptedBlobClientBuilder credential(StorageSharedKeyCredential credential) { this.storageSharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.tokenCredential = null; this.sasToken = null; return this; } /** * Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link AzureNamedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); return credential(StorageSharedKeyCredential.fromAzureNamedKeyCredential(credential)); } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential {@link TokenCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.storageSharedKeyCredential = null; this.sasToken = null; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. This string should only be the query parameters * (with or without a leading '?') and not a full url. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public EncryptedBlobClientBuilder sasToken(String sasToken) { this.sasToken = Objects.requireNonNull(sasToken, "'sasToken' cannot be null."); this.storageSharedKeyCredential = null; this.tokenCredential = null; return this; } /** * Sets the {@link AzureSasCredential} used to authorize requests sent to the service. * * @param credential {@link AzureSasCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureSasCredential credential) { this.azureSasCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Clears the credential used to authorize the request. * * <p>This is for blobs that are publicly accessible.</p> * * @return the updated EncryptedBlobClientBuilder */ public EncryptedBlobClientBuilder setAnonymousAccess() { this.storageSharedKeyCredential = null; this.tokenCredential = null; this.azureSasCredential = null; this.sasToken = null; return this; } /** * Sets the connection string to connect to the service. * * @param connectionString Connection string of the storage account. * @return the updated EncryptedBlobClientBuilder * @throws IllegalArgumentException If {@code connectionString} is invalid. */ @Override public EncryptedBlobClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, LOGGER); StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint(); if (endpoint == null || endpoint.getPrimaryUri() == null) { throw LOGGER .logExceptionAsError(new IllegalArgumentException( "connectionString missing required settings to derive blob service endpoint.")); } this.endpoint(endpoint.getPrimaryUri()); if (storageConnectionString.getAccountName() != null) { this.accountName = storageConnectionString.getAccountName(); } StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings(); if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) { this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name) * * <p>If the blob name contains special characters, pass in the url encoded version of the blob name. </p> * * <p>If the endpoint is to a blob in the root container, this method will fail as it will interpret the blob name * as the container name. With only one path element, it is impossible to distinguish between a container name and a * blob in the root container, so it is assumed to be the container name as this is much more common. When working * with blobs in the root container, it is best to set the endpoint to the account url and specify the blob name * separately using the {@link EncryptedBlobClientBuilder * * @param endpoint URL of the service * @return the updated EncryptedBlobClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ @Override public EncryptedBlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobUrlParts parts = BlobUrlParts.parse(url); this.accountName = parts.getAccountName(); this.endpoint = BuilderHelper.getEndpoint(parts); this.containerName = parts.getBlobContainerName() == null ? this.containerName : parts.getBlobContainerName(); this.blobName = parts.getBlobName() == null ? this.blobName : Utility.urlEncode(parts.getBlobName()); this.snapshot = parts.getSnapshot(); this.versionId = parts.getVersionId(); String sasToken = parts.getCommonSasQueryParameters().encode(); if (!CoreUtils.isNullOrEmpty(sasToken)) { this.sasToken(sasToken); } } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed.", ex)); } return this; } /** * Sets the name of the container that contains the blob. * * @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root}, * will be used. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder containerName(String containerName) { this.containerName = containerName; return this; } /** * Sets the name of the blob. * * @param blobName Name of the blob. If the blob name contains special characters, pass in the url encoded version * of the blob name. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code blobName} is {@code null} */ public EncryptedBlobClientBuilder blobName(String blobName) { this.blobName = Utility.urlEncode(Utility.urlDecode(Objects.requireNonNull(blobName, "'blobName' cannot be null."))); return this; } /** * Sets the snapshot identifier of the blob. * * @param snapshot Snapshot identifier for the blob. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Sets the version identifier of the blob. * * @param versionId Version identifier for the blob, pass {@code null} to interact with the latest blob version. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder versionId(String versionId) { this.versionId = versionId; return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param httpClient The {@link HttpClient} to use for requests. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { LOGGER.info("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param pipelinePolicy A {@link HttpPipelinePolicy pipeline policy}. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ @Override public EncryptedBlobClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"); if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(pipelinePolicy); } else { perRetryPolicies.add(pipelinePolicy); } return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code logOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Gets the default Storage allowlist log headers and query parameters. * * @return the default http log options. */ public static HttpLogOptions getDefaultHttpLogOptions() { return BuilderHelper.getDefaultHttpLogOptions(); } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the request retry options for all the requests made through the client. * * Setting this is mutually exclusive with using {@link * * @param retryOptions {@link RequestRetryOptions}. * @return the updated EncryptedBlobClientBuilder object. */ public EncryptedBlobClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * Consider using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder retryOptions(RetryOptions retryOptions) { this.coreRetryOptions = retryOptions; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * The {@link * {@link * not ignored when {@code pipeline} is set. * * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @see HttpClientOptions * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code clientOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the {@link BlobServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder serviceVersion(BlobServiceVersion version) { this.version = version; return this; } /** * Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server. * * @param customerProvidedKey {@link CustomerProvidedKey} * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) { if (customerProvidedKey == null) { this.customerProvidedKey = null; } else { this.customerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return this; } /** * Sets the {@code encryption scope} that is used to encrypt blob contents on the server. * * @param encryptionScope Encryption scope containing the encryption key information. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder encryptionScope(String encryptionScope) { if (encryptionScope == null) { this.encryptionScope = null; } else { this.encryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return this; } /** * Configures the builder based on the passed {@link BlobClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobClient BlobClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobClient(BlobClient blobClient) { Objects.requireNonNull(blobClient); return client(blobClient.getHttpPipeline(), blobClient.getBlobUrl(), blobClient.getServiceVersion()); } /** * Configures the builder based on the passed {@link BlobAsyncClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobAsyncClient BlobAsyncClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobAsyncClient(BlobAsyncClient blobAsyncClient) { Objects.requireNonNull(blobAsyncClient); return client(blobAsyncClient.getHttpPipeline(), blobAsyncClient.getBlobUrl(), blobAsyncClient.getServiceVersion()); } /** * Helper method to transform a regular client into an encrypted client * * @param httpPipeline {@link HttpPipeline} * @param endpoint The endpoint. * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ private EncryptedBlobClientBuilder client(HttpPipeline httpPipeline, String endpoint, BlobServiceVersion version) { this.endpoint(endpoint); this.serviceVersion(version); return this.pipeline(httpPipeline); } /** * Sets the requires encryption option. * * @param requiresEncryption Whether encryption is enforced by this client. Client will throw if data is * downloaded and it is not encrypted. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder requiresEncryption(boolean requiresEncryption) { this.requiresEncryption = requiresEncryption; return this; } }
class EncryptedBlobClientBuilder implements TokenCredentialTrait<EncryptedBlobClientBuilder>, ConnectionStringTrait<EncryptedBlobClientBuilder>, AzureNamedKeyCredentialTrait<EncryptedBlobClientBuilder>, AzureSasCredentialTrait<EncryptedBlobClientBuilder>, HttpTrait<EncryptedBlobClientBuilder>, ConfigurationTrait<EncryptedBlobClientBuilder>, EndpointTrait<EncryptedBlobClientBuilder> { private static final ClientLogger LOGGER = new ClientLogger(EncryptedBlobClientBuilder.class); private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-storage-blob-cryptography.properties"); private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String CLIENT_NAME = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String BLOB_CLIENT_NAME = USER_AGENT_PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String BLOB_CLIENT_VERSION = USER_AGENT_PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String USER_AGENT_MODIFICATION_REGEX = "(.*? )?(azsdk-java-azure-storage-blob/12\\.\\d{1,2}\\.\\d{1,2}(?:-beta\\.\\d{1,2})?)( .*?)?"; private String endpoint; private String accountName; private String containerName; private String blobName; private String snapshot; private String versionId; private boolean requiresEncryption; private final EncryptionVersion encryptionVersion; private StorageSharedKeyCredential storageSharedKeyCredential; private TokenCredential tokenCredential; private AzureSasCredential azureSasCredential; private String sasToken; private HttpClient httpClient; private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private HttpLogOptions logOptions; private RequestRetryOptions retryOptions; private RetryOptions coreRetryOptions; private HttpPipeline httpPipeline; private ClientOptions clientOptions = new ClientOptions(); private Configuration configuration; private AsyncKeyEncryptionKey keyWrapper; private AsyncKeyEncryptionKeyResolver keyResolver; private String keyWrapAlgorithm; private BlobServiceVersion version; private CpkInfo customerProvidedKey; private EncryptionScope encryptionScope; /** * Creates a new instance of the EncryptedBlobClientBuilder * @deprecated Use {@link EncryptedBlobClientBuilder */ @Deprecated public EncryptedBlobClientBuilder() { logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = EncryptionVersion.V1; LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } /** * Creates a new instance of the EncryptedBlobClientbuilder. * * @param version The version of the client side encryption protocol to use. It is highly recommended that v2 be * preferred for security reasons, though v1 continues to be supported for compatibility reasons. Note that even a * client configured to encrypt using v2 can decrypt blobs that use the v1 protocol. */ public EncryptedBlobClientBuilder(EncryptionVersion version) { Objects.requireNonNull(version); logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = version; if (EncryptionVersion.V1.equals(this.encryptionVersion)) { LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } } /** * Creates a {@link EncryptedBlobClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * <pre> * EncryptedBlobAsyncClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobAsyncClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * * @return a {@link EncryptedBlobClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobClient buildEncryptedBlobClient() { return new EncryptedBlobClient(buildEncryptedBlobAsyncClient()); } /** * Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * <pre> * EncryptedBlobClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * * @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); checkValidEncryptionParameters(); /* Implicit and explicit root container access are functionally equivalent, but explicit references are easier to read and debug. */ if (CoreUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } BlobServiceVersion serviceVersion = version != null ? version : BlobServiceVersion.getLatest(); return new EncryptedBlobAsyncClient(addBlobUserAgentModificationPolicy(getHttpPipeline()), endpoint, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey, encryptionScope, keyWrapper, keyWrapAlgorithm, versionId, encryptionVersion, requiresEncryption); } private HttpPipeline addBlobUserAgentModificationPolicy(HttpPipeline pipeline) { List<HttpPipelinePolicy> policies = new ArrayList<>(); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = pipeline.getPolicy(i); policies.add(currPolicy); if (currPolicy instanceof UserAgentPolicy) { policies.add(new BlobUserAgentModificationPolicy(CLIENT_NAME, CLIENT_VERSION)); } } return new HttpPipelineBuilder() .httpClient(pipeline.getHttpClient()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .tracer(pipeline.getTracer()) .build(); } private HttpPipeline getHttpPipeline() { CredentialValidator.validateSingleCredentialIsPresent( storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, LOGGER); if (httpPipeline != null) { List<HttpPipelinePolicy> policies = new ArrayList<>(); boolean decryptionPolicyPresent = false; for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = httpPipeline.getPolicy(i); if (currPolicy instanceof BlobDecryptionPolicy) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The passed pipeline was already" + " configured for encryption/decryption in a way that might conflict with the passed key " + "information. Please ensure that the passed pipeline is not already configured for " + "encryption/decryption")); } policies.add(currPolicy); } policies.add(0, new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); return new HttpPipelineBuilder() .httpClient(httpPipeline.getHttpClient()) .tracer(httpPipeline.getTracer()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } Configuration userAgentConfiguration = (configuration == null) ? Configuration.NONE : configuration; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); String applicationId = clientOptions.getApplicationId() != null ? clientOptions.getApplicationId() : logOptions.getApplicationId(); String modifiedUserAgent = modifyUserAgentString(applicationId, userAgentConfiguration); policies.add(new UserAgentPolicy(modifiedUserAgent)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(BuilderUtils.createRetryPolicy(retryOptions, coreRetryOptions, LOGGER)); policies.add(new AddDatePolicy()); HttpHeaders headers = new HttpHeaders(); clientOptions.getHeaders().forEach(header -> headers.put(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new MetadataValidationPolicy()); if (storageSharedKeyCredential != null) { policies.add(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)); } else if (tokenCredential != null) { BuilderHelper.httpsValidation(tokenCredential, "bearer token", endpoint, LOGGER); policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, Constants.STORAGE_SCOPE)); } else if (azureSasCredential != null) { policies.add(new AzureSasCredentialPolicy(azureSasCredential, false)); } else if (sasToken != null) { policies.add(new AzureSasCredentialPolicy(new AzureSasCredential(sasToken), false)); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new ResponseValidationPolicyBuilder() .addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID) .addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256) .build()); policies.add(new HttpLoggingPolicy(logOptions)); policies.add(new ScrubEtagPolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(createTracer(clientOptions)) .build(); } /** * Sets the encryption key parameters for the client * * @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key * @param keyWrapAlgorithm The {@link String} used to wrap the key. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) { this.keyWrapper = key; this.keyWrapAlgorithm = keyWrapAlgorithm; return this; } /** * Sets the encryption parameters for this client * * @param keyResolver The key resolver used to select the correct key for decrypting existing blobs. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) { this.keyResolver = keyResolver; return this; } private void checkValidEncryptionParameters() { if (this.keyWrapper == null && this.keyResolver == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null")); } if (this.keyWrapper != null && this.keyWrapAlgorithm == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Key Wrap Algorithm must be specified with a Key.")); } } /** * Sets the {@link StorageSharedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link StorageSharedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ public EncryptedBlobClientBuilder credential(StorageSharedKeyCredential credential) { this.storageSharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.tokenCredential = null; this.sasToken = null; return this; } /** * Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link AzureNamedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); return credential(StorageSharedKeyCredential.fromAzureNamedKeyCredential(credential)); } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential {@link TokenCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.storageSharedKeyCredential = null; this.sasToken = null; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. This string should only be the query parameters * (with or without a leading '?') and not a full url. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public EncryptedBlobClientBuilder sasToken(String sasToken) { this.sasToken = Objects.requireNonNull(sasToken, "'sasToken' cannot be null."); this.storageSharedKeyCredential = null; this.tokenCredential = null; return this; } /** * Sets the {@link AzureSasCredential} used to authorize requests sent to the service. * * @param credential {@link AzureSasCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureSasCredential credential) { this.azureSasCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Clears the credential used to authorize the request. * * <p>This is for blobs that are publicly accessible.</p> * * @return the updated EncryptedBlobClientBuilder */ public EncryptedBlobClientBuilder setAnonymousAccess() { this.storageSharedKeyCredential = null; this.tokenCredential = null; this.azureSasCredential = null; this.sasToken = null; return this; } /** * Sets the connection string to connect to the service. * * @param connectionString Connection string of the storage account. * @return the updated EncryptedBlobClientBuilder * @throws IllegalArgumentException If {@code connectionString} is invalid. */ @Override public EncryptedBlobClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, LOGGER); StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint(); if (endpoint == null || endpoint.getPrimaryUri() == null) { throw LOGGER .logExceptionAsError(new IllegalArgumentException( "connectionString missing required settings to derive blob service endpoint.")); } this.endpoint(endpoint.getPrimaryUri()); if (storageConnectionString.getAccountName() != null) { this.accountName = storageConnectionString.getAccountName(); } StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings(); if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) { this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name) * * <p>If the blob name contains special characters, pass in the url encoded version of the blob name. </p> * * <p>If the endpoint is to a blob in the root container, this method will fail as it will interpret the blob name * as the container name. With only one path element, it is impossible to distinguish between a container name and a * blob in the root container, so it is assumed to be the container name as this is much more common. When working * with blobs in the root container, it is best to set the endpoint to the account url and specify the blob name * separately using the {@link EncryptedBlobClientBuilder * * @param endpoint URL of the service * @return the updated EncryptedBlobClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ @Override public EncryptedBlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobUrlParts parts = BlobUrlParts.parse(url); this.accountName = parts.getAccountName(); this.endpoint = BuilderHelper.getEndpoint(parts); this.containerName = parts.getBlobContainerName() == null ? this.containerName : parts.getBlobContainerName(); this.blobName = parts.getBlobName() == null ? this.blobName : Utility.urlEncode(parts.getBlobName()); this.snapshot = parts.getSnapshot(); this.versionId = parts.getVersionId(); String sasToken = parts.getCommonSasQueryParameters().encode(); if (!CoreUtils.isNullOrEmpty(sasToken)) { this.sasToken(sasToken); } } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed.", ex)); } return this; } /** * Sets the name of the container that contains the blob. * * @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root}, * will be used. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder containerName(String containerName) { this.containerName = containerName; return this; } /** * Sets the name of the blob. * * @param blobName Name of the blob. If the blob name contains special characters, pass in the url encoded version * of the blob name. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code blobName} is {@code null} */ public EncryptedBlobClientBuilder blobName(String blobName) { this.blobName = Utility.urlEncode(Utility.urlDecode(Objects.requireNonNull(blobName, "'blobName' cannot be null."))); return this; } /** * Sets the snapshot identifier of the blob. * * @param snapshot Snapshot identifier for the blob. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Sets the version identifier of the blob. * * @param versionId Version identifier for the blob, pass {@code null} to interact with the latest blob version. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder versionId(String versionId) { this.versionId = versionId; return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param httpClient The {@link HttpClient} to use for requests. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { LOGGER.info("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param pipelinePolicy A {@link HttpPipelinePolicy pipeline policy}. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ @Override public EncryptedBlobClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"); if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(pipelinePolicy); } else { perRetryPolicies.add(pipelinePolicy); } return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code logOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Gets the default Storage allowlist log headers and query parameters. * * @return the default http log options. */ public static HttpLogOptions getDefaultHttpLogOptions() { return BuilderHelper.getDefaultHttpLogOptions(); } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the request retry options for all the requests made through the client. * * Setting this is mutually exclusive with using {@link * * @param retryOptions {@link RequestRetryOptions}. * @return the updated EncryptedBlobClientBuilder object. */ public EncryptedBlobClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * Consider using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder retryOptions(RetryOptions retryOptions) { this.coreRetryOptions = retryOptions; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * The {@link * {@link * not ignored when {@code pipeline} is set. * * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @see HttpClientOptions * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code clientOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the {@link BlobServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder serviceVersion(BlobServiceVersion version) { this.version = version; return this; } /** * Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server. * * @param customerProvidedKey {@link CustomerProvidedKey} * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) { if (customerProvidedKey == null) { this.customerProvidedKey = null; } else { this.customerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return this; } /** * Sets the {@code encryption scope} that is used to encrypt blob contents on the server. * * @param encryptionScope Encryption scope containing the encryption key information. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder encryptionScope(String encryptionScope) { if (encryptionScope == null) { this.encryptionScope = null; } else { this.encryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return this; } /** * Configures the builder based on the passed {@link BlobClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobClient BlobClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobClient(BlobClient blobClient) { Objects.requireNonNull(blobClient); return client(blobClient.getHttpPipeline(), blobClient.getBlobUrl(), blobClient.getServiceVersion()); } /** * Configures the builder based on the passed {@link BlobAsyncClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobAsyncClient BlobAsyncClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobAsyncClient(BlobAsyncClient blobAsyncClient) { Objects.requireNonNull(blobAsyncClient); return client(blobAsyncClient.getHttpPipeline(), blobAsyncClient.getBlobUrl(), blobAsyncClient.getServiceVersion()); } /** * Helper method to transform a regular client into an encrypted client * * @param httpPipeline {@link HttpPipeline} * @param endpoint The endpoint. * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ private EncryptedBlobClientBuilder client(HttpPipeline httpPipeline, String endpoint, BlobServiceVersion version) { this.endpoint(endpoint); this.serviceVersion(version); return this.pipeline(httpPipeline); } /** * Sets the requires encryption option. * * @param requiresEncryption Whether encryption is enforced by this client. Client will throw if data is * downloaded and it is not encrypted. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder requiresEncryption(boolean requiresEncryption) { this.requiresEncryption = requiresEncryption; return this; } }
can you add a bit more comment about why here?
public void shouldMonitor() throws InterruptedException, MalformedURLException { SpringMonitorTest.class.getResourceAsStream("/logback.xml"); String response = restTemplate.getForObject(Controller.URL, String.class); assertThat(response).isEqualTo("OK!"); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.url) .isEqualTo(new URL("https: List<TelemetryItem> telemetryItems = customValidationPolicy.actualTelemetryItems; List<String> telemetryTypes = telemetryItems.stream().map(telemetry -> telemetry.getName()).collect(Collectors.toList()); assertThat(telemetryItems.size()).as("Telemetry: " + telemetryTypes).isEqualTo(5); List<TelemetryItem> logs = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Message")) .collect(Collectors.toList()); assertThat(logs).hasSize(3); TelemetryItem firstLogTelemetry = logs.get(0); MonitorDomain logBaseData = firstLogTelemetry.getData().getBaseData(); MessageData logData = (MessageData) logBaseData; assertThat(logData.getMessage()) .isEqualTo("Initializing Spring DispatcherServlet 'dispatcherServlet'"); assertThat(logData.getSeverityLevel()).isEqualTo(SeverityLevel.INFORMATION); List<TelemetryItem> remoteDependencies = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("RemoteDependency")) .collect(Collectors.toList()); assertThat(remoteDependencies).hasSize(1); TelemetryItem remoteDependency = remoteDependencies.get(0); MonitorDomain remoteBaseData = remoteDependency.getData().getBaseData(); RemoteDependencyData remoteDependencyData = (RemoteDependencyData) remoteBaseData; assertThat(remoteDependencyData.getType()).isEqualTo("SQL"); assertThat(remoteDependencyData.getData()) .isEqualTo("create table test_table (id bigint not null, primary key (id))"); List<TelemetryItem> requests = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Request")) .collect(Collectors.toList()); TelemetryItem request = requests.get(0); MonitorDomain requestBaseData = request.getData().getBaseData(); RequestData requestData = (RequestData) requestBaseData; assertThat(requestData.getUrl()).contains(Controller.URL); assertThat(requestData.isSuccess()).isTrue(); assertThat(requestData.getResponseCode()).isEqualTo("200"); assertThat(requestData.getName()).isEqualTo("GET /controller-url"); }
SpringMonitorTest.class.getResourceAsStream("/logback.xml");
public void shouldMonitor() throws InterruptedException, MalformedURLException { SpringMonitorTest.class.getResourceAsStream("/logback.xml"); String response = restTemplate.getForObject(Controller.URL, String.class); assertThat(response).isEqualTo("OK!"); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.url) .isEqualTo(new URL("https: List<TelemetryItem> telemetryItems = customValidationPolicy.actualTelemetryItems; List<String> telemetryTypes = telemetryItems.stream().map(telemetry -> telemetry.getName()).collect(Collectors.toList()); assertThat(telemetryItems.size()).as("Telemetry: " + telemetryTypes).isEqualTo(5); List<TelemetryItem> logs = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Message")) .collect(Collectors.toList()); assertThat(logs).hasSize(3); TelemetryItem firstLogTelemetry = logs.get(0); MonitorDomain logBaseData = firstLogTelemetry.getData().getBaseData(); MessageData logData = (MessageData) logBaseData; assertThat(logData.getMessage()) .isEqualTo("Initializing Spring DispatcherServlet 'dispatcherServlet'"); assertThat(logData.getSeverityLevel()).isEqualTo(SeverityLevel.INFORMATION); List<TelemetryItem> remoteDependencies = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("RemoteDependency")) .collect(Collectors.toList()); assertThat(remoteDependencies).hasSize(1); TelemetryItem remoteDependency = remoteDependencies.get(0); MonitorDomain remoteBaseData = remoteDependency.getData().getBaseData(); RemoteDependencyData remoteDependencyData = (RemoteDependencyData) remoteBaseData; assertThat(remoteDependencyData.getType()).isEqualTo("SQL"); assertThat(remoteDependencyData.getData()) .isEqualTo("create table test_table (id bigint not null, primary key (id))"); List<TelemetryItem> requests = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Request")) .collect(Collectors.toList()); TelemetryItem request = requests.get(0); MonitorDomain requestBaseData = request.getData().getBaseData(); RequestData requestData = (RequestData) requestBaseData; assertThat(requestData.getUrl()).contains(Controller.URL); assertThat(requestData.isSuccess()).isTrue(); assertThat(requestData.getResponseCode()).isEqualTo("200"); assertThat(requestData.getName()).isEqualTo("GET /controller-url"); }
class TestConfiguration { @Bean HttpPipeline httpPipeline() { countDownLatch = new CountDownLatch(2); customValidationPolicy = new CustomValidationPolicy(countDownLatch); return getHttpPipeline(customValidationPolicy); } HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy) { return new HttpPipelineBuilder() .httpClient(HttpClient.createDefault()) .policies(policy) .build(); } }
class TestConfiguration { @Bean HttpPipeline httpPipeline() { countDownLatch = new CountDownLatch(2); customValidationPolicy = new CustomValidationPolicy(countDownLatch); return getHttpPipeline(customValidationPolicy); } HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy) { return new HttpPipelineBuilder() .httpClient(HttpClient.createDefault()) .policies(policy) .build(); } }
The log telemetry did not work because the OTel Logback appender was not added to Logback. I have added this code line to have more insights. And it fixes the issue. I don't know why. It seems a Logback issue with GraalVM native.
public void shouldMonitor() throws InterruptedException, MalformedURLException { SpringMonitorTest.class.getResourceAsStream("/logback.xml"); String response = restTemplate.getForObject(Controller.URL, String.class); assertThat(response).isEqualTo("OK!"); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.url) .isEqualTo(new URL("https: List<TelemetryItem> telemetryItems = customValidationPolicy.actualTelemetryItems; List<String> telemetryTypes = telemetryItems.stream().map(telemetry -> telemetry.getName()).collect(Collectors.toList()); assertThat(telemetryItems.size()).as("Telemetry: " + telemetryTypes).isEqualTo(5); List<TelemetryItem> logs = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Message")) .collect(Collectors.toList()); assertThat(logs).hasSize(3); TelemetryItem firstLogTelemetry = logs.get(0); MonitorDomain logBaseData = firstLogTelemetry.getData().getBaseData(); MessageData logData = (MessageData) logBaseData; assertThat(logData.getMessage()) .isEqualTo("Initializing Spring DispatcherServlet 'dispatcherServlet'"); assertThat(logData.getSeverityLevel()).isEqualTo(SeverityLevel.INFORMATION); List<TelemetryItem> remoteDependencies = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("RemoteDependency")) .collect(Collectors.toList()); assertThat(remoteDependencies).hasSize(1); TelemetryItem remoteDependency = remoteDependencies.get(0); MonitorDomain remoteBaseData = remoteDependency.getData().getBaseData(); RemoteDependencyData remoteDependencyData = (RemoteDependencyData) remoteBaseData; assertThat(remoteDependencyData.getType()).isEqualTo("SQL"); assertThat(remoteDependencyData.getData()) .isEqualTo("create table test_table (id bigint not null, primary key (id))"); List<TelemetryItem> requests = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Request")) .collect(Collectors.toList()); TelemetryItem request = requests.get(0); MonitorDomain requestBaseData = request.getData().getBaseData(); RequestData requestData = (RequestData) requestBaseData; assertThat(requestData.getUrl()).contains(Controller.URL); assertThat(requestData.isSuccess()).isTrue(); assertThat(requestData.getResponseCode()).isEqualTo("200"); assertThat(requestData.getName()).isEqualTo("GET /controller-url"); }
SpringMonitorTest.class.getResourceAsStream("/logback.xml");
public void shouldMonitor() throws InterruptedException, MalformedURLException { SpringMonitorTest.class.getResourceAsStream("/logback.xml"); String response = restTemplate.getForObject(Controller.URL, String.class); assertThat(response).isEqualTo("OK!"); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.url) .isEqualTo(new URL("https: List<TelemetryItem> telemetryItems = customValidationPolicy.actualTelemetryItems; List<String> telemetryTypes = telemetryItems.stream().map(telemetry -> telemetry.getName()).collect(Collectors.toList()); assertThat(telemetryItems.size()).as("Telemetry: " + telemetryTypes).isEqualTo(5); List<TelemetryItem> logs = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Message")) .collect(Collectors.toList()); assertThat(logs).hasSize(3); TelemetryItem firstLogTelemetry = logs.get(0); MonitorDomain logBaseData = firstLogTelemetry.getData().getBaseData(); MessageData logData = (MessageData) logBaseData; assertThat(logData.getMessage()) .isEqualTo("Initializing Spring DispatcherServlet 'dispatcherServlet'"); assertThat(logData.getSeverityLevel()).isEqualTo(SeverityLevel.INFORMATION); List<TelemetryItem> remoteDependencies = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("RemoteDependency")) .collect(Collectors.toList()); assertThat(remoteDependencies).hasSize(1); TelemetryItem remoteDependency = remoteDependencies.get(0); MonitorDomain remoteBaseData = remoteDependency.getData().getBaseData(); RemoteDependencyData remoteDependencyData = (RemoteDependencyData) remoteBaseData; assertThat(remoteDependencyData.getType()).isEqualTo("SQL"); assertThat(remoteDependencyData.getData()) .isEqualTo("create table test_table (id bigint not null, primary key (id))"); List<TelemetryItem> requests = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Request")) .collect(Collectors.toList()); TelemetryItem request = requests.get(0); MonitorDomain requestBaseData = request.getData().getBaseData(); RequestData requestData = (RequestData) requestBaseData; assertThat(requestData.getUrl()).contains(Controller.URL); assertThat(requestData.isSuccess()).isTrue(); assertThat(requestData.getResponseCode()).isEqualTo("200"); assertThat(requestData.getName()).isEqualTo("GET /controller-url"); }
class TestConfiguration { @Bean HttpPipeline httpPipeline() { countDownLatch = new CountDownLatch(2); customValidationPolicy = new CustomValidationPolicy(countDownLatch); return getHttpPipeline(customValidationPolicy); } HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy) { return new HttpPipelineBuilder() .httpClient(HttpClient.createDefault()) .policies(policy) .build(); } }
class TestConfiguration { @Bean HttpPipeline httpPipeline() { countDownLatch = new CountDownLatch(2); customValidationPolicy = new CustomValidationPolicy(countDownLatch); return getHttpPipeline(customValidationPolicy); } HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy) { return new HttpPipelineBuilder() .httpClient(HttpClient.createDefault()) .policies(policy) .build(); } }
```suggestion // Only required with GraalVM native test execution // we aren't sure why this is needed, seems to be a Logback issue with GraalVM native ```
public void shouldMonitor() throws InterruptedException, MalformedURLException { SpringMonitorTest.class.getResourceAsStream("/logback.xml"); String response = restTemplate.getForObject(Controller.URL, String.class); assertThat(response).isEqualTo("OK!"); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.url) .isEqualTo(new URL("https: List<TelemetryItem> telemetryItems = customValidationPolicy.actualTelemetryItems; List<String> telemetryTypes = telemetryItems.stream().map(telemetry -> telemetry.getName()).collect(Collectors.toList()); assertThat(telemetryItems.size()).as("Telemetry: " + telemetryTypes).isEqualTo(5); List<TelemetryItem> logs = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Message")) .collect(Collectors.toList()); assertThat(logs).hasSize(3); TelemetryItem firstLogTelemetry = logs.get(0); MonitorDomain logBaseData = firstLogTelemetry.getData().getBaseData(); MessageData logData = (MessageData) logBaseData; assertThat(logData.getMessage()) .isEqualTo("Initializing Spring DispatcherServlet 'dispatcherServlet'"); assertThat(logData.getSeverityLevel()).isEqualTo(SeverityLevel.INFORMATION); List<TelemetryItem> remoteDependencies = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("RemoteDependency")) .collect(Collectors.toList()); assertThat(remoteDependencies).hasSize(1); TelemetryItem remoteDependency = remoteDependencies.get(0); MonitorDomain remoteBaseData = remoteDependency.getData().getBaseData(); RemoteDependencyData remoteDependencyData = (RemoteDependencyData) remoteBaseData; assertThat(remoteDependencyData.getType()).isEqualTo("SQL"); assertThat(remoteDependencyData.getData()) .isEqualTo("create table test_table (id bigint not null, primary key (id))"); List<TelemetryItem> requests = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Request")) .collect(Collectors.toList()); TelemetryItem request = requests.get(0); MonitorDomain requestBaseData = request.getData().getBaseData(); RequestData requestData = (RequestData) requestBaseData; assertThat(requestData.getUrl()).contains(Controller.URL); assertThat(requestData.isSuccess()).isTrue(); assertThat(requestData.getResponseCode()).isEqualTo("200"); assertThat(requestData.getName()).isEqualTo("GET /controller-url"); }
public void shouldMonitor() throws InterruptedException, MalformedURLException { SpringMonitorTest.class.getResourceAsStream("/logback.xml"); String response = restTemplate.getForObject(Controller.URL, String.class); assertThat(response).isEqualTo("OK!"); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.url) .isEqualTo(new URL("https: List<TelemetryItem> telemetryItems = customValidationPolicy.actualTelemetryItems; List<String> telemetryTypes = telemetryItems.stream().map(telemetry -> telemetry.getName()).collect(Collectors.toList()); assertThat(telemetryItems.size()).as("Telemetry: " + telemetryTypes).isEqualTo(5); List<TelemetryItem> logs = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Message")) .collect(Collectors.toList()); assertThat(logs).hasSize(3); TelemetryItem firstLogTelemetry = logs.get(0); MonitorDomain logBaseData = firstLogTelemetry.getData().getBaseData(); MessageData logData = (MessageData) logBaseData; assertThat(logData.getMessage()) .isEqualTo("Initializing Spring DispatcherServlet 'dispatcherServlet'"); assertThat(logData.getSeverityLevel()).isEqualTo(SeverityLevel.INFORMATION); List<TelemetryItem> remoteDependencies = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("RemoteDependency")) .collect(Collectors.toList()); assertThat(remoteDependencies).hasSize(1); TelemetryItem remoteDependency = remoteDependencies.get(0); MonitorDomain remoteBaseData = remoteDependency.getData().getBaseData(); RemoteDependencyData remoteDependencyData = (RemoteDependencyData) remoteBaseData; assertThat(remoteDependencyData.getType()).isEqualTo("SQL"); assertThat(remoteDependencyData.getData()) .isEqualTo("create table test_table (id bigint not null, primary key (id))"); List<TelemetryItem> requests = telemetryItems.stream() .filter(telemetry -> telemetry.getName().equals("Request")) .collect(Collectors.toList()); TelemetryItem request = requests.get(0); MonitorDomain requestBaseData = request.getData().getBaseData(); RequestData requestData = (RequestData) requestBaseData; assertThat(requestData.getUrl()).contains(Controller.URL); assertThat(requestData.isSuccess()).isTrue(); assertThat(requestData.getResponseCode()).isEqualTo("200"); assertThat(requestData.getName()).isEqualTo("GET /controller-url"); }
class TestConfiguration { @Bean HttpPipeline httpPipeline() { countDownLatch = new CountDownLatch(2); customValidationPolicy = new CustomValidationPolicy(countDownLatch); return getHttpPipeline(customValidationPolicy); } HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy) { return new HttpPipelineBuilder() .httpClient(HttpClient.createDefault()) .policies(policy) .build(); } }
class TestConfiguration { @Bean HttpPipeline httpPipeline() { countDownLatch = new CountDownLatch(2); customValidationPolicy = new CustomValidationPolicy(countDownLatch); return getHttpPipeline(customValidationPolicy); } HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy) { return new HttpPipelineBuilder() .httpClient(HttpClient.createDefault()) .policies(policy) .build(); } }
Just want to be sure this is a "per-call" policy and not "per-retry"? We need to make sure this string isn't added multiple times per request if there are retries. If we're not sure, you can also add a check to the policy to check if the additional string is not already present before adding it.
private HttpPipeline getHttpPipeline() { CredentialValidator.validateSingleCredentialIsPresent( storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, LOGGER); if (httpPipeline != null) { List<HttpPipelinePolicy> policies = new ArrayList<>(); boolean decryptionPolicyPresent = false; for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = httpPipeline.getPolicy(i); if (currPolicy instanceof BlobDecryptionPolicy) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The passed pipeline was already" + " configured for encryption/decryption in a way that might conflict with the passed key " + "information. Please ensure that the passed pipeline is not already configured for " + "encryption/decryption")); } policies.add(currPolicy); } policies.add(0, new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); return new HttpPipelineBuilder() .httpClient(httpPipeline.getHttpClient()) .tracer(httpPipeline.getTracer()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } Configuration userAgentConfiguration = (configuration == null) ? Configuration.NONE : configuration; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); String applicationId = clientOptions.getApplicationId() != null ? clientOptions.getApplicationId() : logOptions.getApplicationId(); String modifiedUserAgent = modifyUserAgentString(applicationId, userAgentConfiguration); policies.add(new UserAgentPolicy(modifiedUserAgent)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(BuilderUtils.createRetryPolicy(retryOptions, coreRetryOptions, LOGGER)); policies.add(new AddDatePolicy()); HttpHeaders headers = new HttpHeaders(); clientOptions.getHeaders().forEach(header -> headers.put(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new MetadataValidationPolicy()); if (storageSharedKeyCredential != null) { policies.add(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)); } else if (tokenCredential != null) { BuilderHelper.httpsValidation(tokenCredential, "bearer token", endpoint, LOGGER); policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, Constants.STORAGE_SCOPE)); } else if (azureSasCredential != null) { policies.add(new AzureSasCredentialPolicy(azureSasCredential, false)); } else if (sasToken != null) { policies.add(new AzureSasCredentialPolicy(new AzureSasCredential(sasToken), false)); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new ResponseValidationPolicyBuilder() .addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID) .addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256) .build()); policies.add(new HttpLoggingPolicy(logOptions)); policies.add(new ScrubEtagPolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(createTracer(clientOptions)) .build(); }
policies.add(new UserAgentPolicy(modifiedUserAgent));
private HttpPipeline getHttpPipeline() { CredentialValidator.validateSingleCredentialIsPresent( storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, LOGGER); if (httpPipeline != null) { List<HttpPipelinePolicy> policies = new ArrayList<>(); boolean decryptionPolicyPresent = false; for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = httpPipeline.getPolicy(i); if (currPolicy instanceof BlobDecryptionPolicy) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The passed pipeline was already" + " configured for encryption/decryption in a way that might conflict with the passed key " + "information. Please ensure that the passed pipeline is not already configured for " + "encryption/decryption")); } policies.add(currPolicy); } policies.add(0, new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); return new HttpPipelineBuilder() .httpClient(httpPipeline.getHttpClient()) .tracer(httpPipeline.getTracer()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } Configuration userAgentConfiguration = (configuration == null) ? Configuration.NONE : configuration; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); String applicationId = clientOptions.getApplicationId() != null ? clientOptions.getApplicationId() : logOptions.getApplicationId(); String modifiedUserAgent = modifyUserAgentString(applicationId, userAgentConfiguration); policies.add(new UserAgentPolicy(modifiedUserAgent)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(BuilderUtils.createRetryPolicy(retryOptions, coreRetryOptions, LOGGER)); policies.add(new AddDatePolicy()); HttpHeaders headers = new HttpHeaders(); clientOptions.getHeaders().forEach(header -> headers.put(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new MetadataValidationPolicy()); if (storageSharedKeyCredential != null) { policies.add(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)); } else if (tokenCredential != null) { BuilderHelper.httpsValidation(tokenCredential, "bearer token", endpoint, LOGGER); policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, Constants.STORAGE_SCOPE)); } else if (azureSasCredential != null) { policies.add(new AzureSasCredentialPolicy(azureSasCredential, false)); } else if (sasToken != null) { policies.add(new AzureSasCredentialPolicy(new AzureSasCredential(sasToken), false)); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new ResponseValidationPolicyBuilder() .addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID) .addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256) .build()); policies.add(new HttpLoggingPolicy(logOptions)); policies.add(new ScrubEtagPolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(createTracer(clientOptions)) .build(); }
class EncryptedBlobClientBuilder implements TokenCredentialTrait<EncryptedBlobClientBuilder>, ConnectionStringTrait<EncryptedBlobClientBuilder>, AzureNamedKeyCredentialTrait<EncryptedBlobClientBuilder>, AzureSasCredentialTrait<EncryptedBlobClientBuilder>, HttpTrait<EncryptedBlobClientBuilder>, ConfigurationTrait<EncryptedBlobClientBuilder>, EndpointTrait<EncryptedBlobClientBuilder> { private static final ClientLogger LOGGER = new ClientLogger(EncryptedBlobClientBuilder.class); private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-storage-blob-cryptography.properties"); private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String CLIENT_NAME = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String BLOB_CLIENT_NAME = USER_AGENT_PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String BLOB_CLIENT_VERSION = USER_AGENT_PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String USER_AGENT_MODIFICATION_REGEX = "(.*? )?(azsdk-java-azure-storage-blob/12\\.\\d{1,2}\\.\\d{1,2}(?:-beta\\.\\d{1,2})?)( .*?)?"; private String endpoint; private String accountName; private String containerName; private String blobName; private String snapshot; private String versionId; private boolean requiresEncryption; private final EncryptionVersion encryptionVersion; private StorageSharedKeyCredential storageSharedKeyCredential; private TokenCredential tokenCredential; private AzureSasCredential azureSasCredential; private String sasToken; private HttpClient httpClient; private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private HttpLogOptions logOptions; private RequestRetryOptions retryOptions; private RetryOptions coreRetryOptions; private HttpPipeline httpPipeline; private ClientOptions clientOptions = new ClientOptions(); private Configuration configuration; private AsyncKeyEncryptionKey keyWrapper; private AsyncKeyEncryptionKeyResolver keyResolver; private String keyWrapAlgorithm; private BlobServiceVersion version; private CpkInfo customerProvidedKey; private EncryptionScope encryptionScope; /** * Creates a new instance of the EncryptedBlobClientBuilder * @deprecated Use {@link EncryptedBlobClientBuilder */ @Deprecated public EncryptedBlobClientBuilder() { logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = EncryptionVersion.V1; LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } /** * Creates a new instance of the EncryptedBlobClientbuilder. * * @param version The version of the client side encryption protocol to use. It is highly recommended that v2 be * preferred for security reasons, though v1 continues to be supported for compatibility reasons. Note that even a * client configured to encrypt using v2 can decrypt blobs that use the v1 protocol. */ public EncryptedBlobClientBuilder(EncryptionVersion version) { Objects.requireNonNull(version); logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = version; if (EncryptionVersion.V1.equals(this.encryptionVersion)) { LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } } /** * Creates a {@link EncryptedBlobClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * <pre> * EncryptedBlobAsyncClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobAsyncClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * * @return a {@link EncryptedBlobClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobClient buildEncryptedBlobClient() { return new EncryptedBlobClient(buildEncryptedBlobAsyncClient()); } /** * Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * <pre> * EncryptedBlobClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * * @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); checkValidEncryptionParameters(); /* Implicit and explicit root container access are functionally equivalent, but explicit references are easier to read and debug. */ if (CoreUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } BlobServiceVersion serviceVersion = version != null ? version : BlobServiceVersion.getLatest(); return new EncryptedBlobAsyncClient(addBlobUserAgentModificationPolicy(getHttpPipeline()), endpoint, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey, encryptionScope, keyWrapper, keyWrapAlgorithm, versionId, encryptionVersion, requiresEncryption); } private HttpPipeline addBlobUserAgentModificationPolicy(HttpPipeline pipeline) { List<HttpPipelinePolicy> policies = new ArrayList<>(); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = pipeline.getPolicy(i); policies.add(currPolicy); if (currPolicy instanceof UserAgentPolicy) { policies.add(new BlobUserAgentModificationPolicy(CLIENT_NAME, CLIENT_VERSION)); } } return new HttpPipelineBuilder() .httpClient(pipeline.getHttpClient()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .tracer(pipeline.getTracer()) .build(); } private String modifyUserAgentString(String applicationId, Configuration userAgentConfiguration) { Pattern pattern = Pattern.compile(USER_AGENT_MODIFICATION_REGEX); String userAgent = UserAgentUtil.toUserAgentString(applicationId, BLOB_CLIENT_NAME, BLOB_CLIENT_VERSION, userAgentConfiguration); Matcher matcher = pattern.matcher(userAgent); String version = encryptionVersion == EncryptionVersion.V2 ? "2.0" : "1.0"; String stringToAppend = "azstorage-clientsideencryption/" + version; if (matcher.matches()) { String segment1 = matcher.group(1) == null ? "" : matcher.group(1); String segment2 = matcher.group(2) == null ? "" : matcher.group(2); String segment3 = matcher.group(3) == null ? "" : matcher.group(3); userAgent = segment1 + stringToAppend + " " + segment2 + segment3; } return userAgent; } /** * Sets the encryption key parameters for the client * * @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key * @param keyWrapAlgorithm The {@link String} used to wrap the key. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) { this.keyWrapper = key; this.keyWrapAlgorithm = keyWrapAlgorithm; return this; } /** * Sets the encryption parameters for this client * * @param keyResolver The key resolver used to select the correct key for decrypting existing blobs. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) { this.keyResolver = keyResolver; return this; } private void checkValidEncryptionParameters() { if (this.keyWrapper == null && this.keyResolver == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null")); } if (this.keyWrapper != null && this.keyWrapAlgorithm == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Key Wrap Algorithm must be specified with a Key.")); } } /** * Sets the {@link StorageSharedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link StorageSharedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ public EncryptedBlobClientBuilder credential(StorageSharedKeyCredential credential) { this.storageSharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.tokenCredential = null; this.sasToken = null; return this; } /** * Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link AzureNamedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); return credential(StorageSharedKeyCredential.fromAzureNamedKeyCredential(credential)); } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential {@link TokenCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.storageSharedKeyCredential = null; this.sasToken = null; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. This string should only be the query parameters * (with or without a leading '?') and not a full url. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public EncryptedBlobClientBuilder sasToken(String sasToken) { this.sasToken = Objects.requireNonNull(sasToken, "'sasToken' cannot be null."); this.storageSharedKeyCredential = null; this.tokenCredential = null; return this; } /** * Sets the {@link AzureSasCredential} used to authorize requests sent to the service. * * @param credential {@link AzureSasCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureSasCredential credential) { this.azureSasCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Clears the credential used to authorize the request. * * <p>This is for blobs that are publicly accessible.</p> * * @return the updated EncryptedBlobClientBuilder */ public EncryptedBlobClientBuilder setAnonymousAccess() { this.storageSharedKeyCredential = null; this.tokenCredential = null; this.azureSasCredential = null; this.sasToken = null; return this; } /** * Sets the connection string to connect to the service. * * @param connectionString Connection string of the storage account. * @return the updated EncryptedBlobClientBuilder * @throws IllegalArgumentException If {@code connectionString} is invalid. */ @Override public EncryptedBlobClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, LOGGER); StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint(); if (endpoint == null || endpoint.getPrimaryUri() == null) { throw LOGGER .logExceptionAsError(new IllegalArgumentException( "connectionString missing required settings to derive blob service endpoint.")); } this.endpoint(endpoint.getPrimaryUri()); if (storageConnectionString.getAccountName() != null) { this.accountName = storageConnectionString.getAccountName(); } StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings(); if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) { this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name) * * <p>If the blob name contains special characters, pass in the url encoded version of the blob name. </p> * * <p>If the endpoint is to a blob in the root container, this method will fail as it will interpret the blob name * as the container name. With only one path element, it is impossible to distinguish between a container name and a * blob in the root container, so it is assumed to be the container name as this is much more common. When working * with blobs in the root container, it is best to set the endpoint to the account url and specify the blob name * separately using the {@link EncryptedBlobClientBuilder * * @param endpoint URL of the service * @return the updated EncryptedBlobClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ @Override public EncryptedBlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobUrlParts parts = BlobUrlParts.parse(url); this.accountName = parts.getAccountName(); this.endpoint = BuilderHelper.getEndpoint(parts); this.containerName = parts.getBlobContainerName() == null ? this.containerName : parts.getBlobContainerName(); this.blobName = parts.getBlobName() == null ? this.blobName : Utility.urlEncode(parts.getBlobName()); this.snapshot = parts.getSnapshot(); this.versionId = parts.getVersionId(); String sasToken = parts.getCommonSasQueryParameters().encode(); if (!CoreUtils.isNullOrEmpty(sasToken)) { this.sasToken(sasToken); } } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed.", ex)); } return this; } /** * Sets the name of the container that contains the blob. * * @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root}, * will be used. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder containerName(String containerName) { this.containerName = containerName; return this; } /** * Sets the name of the blob. * * @param blobName Name of the blob. If the blob name contains special characters, pass in the url encoded version * of the blob name. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code blobName} is {@code null} */ public EncryptedBlobClientBuilder blobName(String blobName) { this.blobName = Utility.urlEncode(Utility.urlDecode(Objects.requireNonNull(blobName, "'blobName' cannot be null."))); return this; } /** * Sets the snapshot identifier of the blob. * * @param snapshot Snapshot identifier for the blob. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Sets the version identifier of the blob. * * @param versionId Version identifier for the blob, pass {@code null} to interact with the latest blob version. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder versionId(String versionId) { this.versionId = versionId; return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param httpClient The {@link HttpClient} to use for requests. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { LOGGER.info("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param pipelinePolicy A {@link HttpPipelinePolicy pipeline policy}. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ @Override public EncryptedBlobClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"); if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(pipelinePolicy); } else { perRetryPolicies.add(pipelinePolicy); } return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code logOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Gets the default Storage allowlist log headers and query parameters. * * @return the default http log options. */ public static HttpLogOptions getDefaultHttpLogOptions() { return BuilderHelper.getDefaultHttpLogOptions(); } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the request retry options for all the requests made through the client. * * Setting this is mutually exclusive with using {@link * * @param retryOptions {@link RequestRetryOptions}. * @return the updated EncryptedBlobClientBuilder object. */ public EncryptedBlobClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * Consider using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder retryOptions(RetryOptions retryOptions) { this.coreRetryOptions = retryOptions; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * The {@link * {@link * not ignored when {@code pipeline} is set. * * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @see HttpClientOptions * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code clientOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the {@link BlobServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder serviceVersion(BlobServiceVersion version) { this.version = version; return this; } /** * Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server. * * @param customerProvidedKey {@link CustomerProvidedKey} * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) { if (customerProvidedKey == null) { this.customerProvidedKey = null; } else { this.customerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return this; } /** * Sets the {@code encryption scope} that is used to encrypt blob contents on the server. * * @param encryptionScope Encryption scope containing the encryption key information. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder encryptionScope(String encryptionScope) { if (encryptionScope == null) { this.encryptionScope = null; } else { this.encryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return this; } /** * Configures the builder based on the passed {@link BlobClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobClient BlobClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobClient(BlobClient blobClient) { Objects.requireNonNull(blobClient); return client(blobClient.getHttpPipeline(), blobClient.getBlobUrl(), blobClient.getServiceVersion()); } /** * Configures the builder based on the passed {@link BlobAsyncClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobAsyncClient BlobAsyncClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobAsyncClient(BlobAsyncClient blobAsyncClient) { Objects.requireNonNull(blobAsyncClient); return client(blobAsyncClient.getHttpPipeline(), blobAsyncClient.getBlobUrl(), blobAsyncClient.getServiceVersion()); } /** * Helper method to transform a regular client into an encrypted client * * @param httpPipeline {@link HttpPipeline} * @param endpoint The endpoint. * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ private EncryptedBlobClientBuilder client(HttpPipeline httpPipeline, String endpoint, BlobServiceVersion version) { this.endpoint(endpoint); this.serviceVersion(version); return this.pipeline(httpPipeline); } /** * Sets the requires encryption option. * * @param requiresEncryption Whether encryption is enforced by this client. Client will throw if data is * downloaded and it is not encrypted. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder requiresEncryption(boolean requiresEncryption) { this.requiresEncryption = requiresEncryption; return this; } }
class EncryptedBlobClientBuilder implements TokenCredentialTrait<EncryptedBlobClientBuilder>, ConnectionStringTrait<EncryptedBlobClientBuilder>, AzureNamedKeyCredentialTrait<EncryptedBlobClientBuilder>, AzureSasCredentialTrait<EncryptedBlobClientBuilder>, HttpTrait<EncryptedBlobClientBuilder>, ConfigurationTrait<EncryptedBlobClientBuilder>, EndpointTrait<EncryptedBlobClientBuilder> { private static final ClientLogger LOGGER = new ClientLogger(EncryptedBlobClientBuilder.class); private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-storage-blob-cryptography.properties"); private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String CLIENT_NAME = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String BLOB_CLIENT_NAME = USER_AGENT_PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String BLOB_CLIENT_VERSION = USER_AGENT_PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String USER_AGENT_MODIFICATION_REGEX = "(.*? )?(azsdk-java-azure-storage-blob/12\\.\\d{1,2}\\.\\d{1,2}(?:-beta\\.\\d{1,2})?)( .*?)?"; private String endpoint; private String accountName; private String containerName; private String blobName; private String snapshot; private String versionId; private boolean requiresEncryption; private final EncryptionVersion encryptionVersion; private StorageSharedKeyCredential storageSharedKeyCredential; private TokenCredential tokenCredential; private AzureSasCredential azureSasCredential; private String sasToken; private HttpClient httpClient; private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private HttpLogOptions logOptions; private RequestRetryOptions retryOptions; private RetryOptions coreRetryOptions; private HttpPipeline httpPipeline; private ClientOptions clientOptions = new ClientOptions(); private Configuration configuration; private AsyncKeyEncryptionKey keyWrapper; private AsyncKeyEncryptionKeyResolver keyResolver; private String keyWrapAlgorithm; private BlobServiceVersion version; private CpkInfo customerProvidedKey; private EncryptionScope encryptionScope; /** * Creates a new instance of the EncryptedBlobClientBuilder * @deprecated Use {@link EncryptedBlobClientBuilder */ @Deprecated public EncryptedBlobClientBuilder() { logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = EncryptionVersion.V1; LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } /** * Creates a new instance of the EncryptedBlobClientbuilder. * * @param version The version of the client side encryption protocol to use. It is highly recommended that v2 be * preferred for security reasons, though v1 continues to be supported for compatibility reasons. Note that even a * client configured to encrypt using v2 can decrypt blobs that use the v1 protocol. */ public EncryptedBlobClientBuilder(EncryptionVersion version) { Objects.requireNonNull(version); logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = version; if (EncryptionVersion.V1.equals(this.encryptionVersion)) { LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } } /** * Creates a {@link EncryptedBlobClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * <pre> * EncryptedBlobAsyncClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobAsyncClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * * @return a {@link EncryptedBlobClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobClient buildEncryptedBlobClient() { return new EncryptedBlobClient(buildEncryptedBlobAsyncClient()); } /** * Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * <pre> * EncryptedBlobClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * * @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); checkValidEncryptionParameters(); /* Implicit and explicit root container access are functionally equivalent, but explicit references are easier to read and debug. */ if (CoreUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } BlobServiceVersion serviceVersion = version != null ? version : BlobServiceVersion.getLatest(); return new EncryptedBlobAsyncClient(addBlobUserAgentModificationPolicy(getHttpPipeline()), endpoint, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey, encryptionScope, keyWrapper, keyWrapAlgorithm, versionId, encryptionVersion, requiresEncryption); } private HttpPipeline addBlobUserAgentModificationPolicy(HttpPipeline pipeline) { List<HttpPipelinePolicy> policies = new ArrayList<>(); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = pipeline.getPolicy(i); policies.add(currPolicy); if (currPolicy instanceof UserAgentPolicy) { policies.add(new BlobUserAgentModificationPolicy(CLIENT_NAME, CLIENT_VERSION)); } } return new HttpPipelineBuilder() .httpClient(pipeline.getHttpClient()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .tracer(pipeline.getTracer()) .build(); } private String modifyUserAgentString(String applicationId, Configuration userAgentConfiguration) { Pattern pattern = Pattern.compile(USER_AGENT_MODIFICATION_REGEX); String userAgent = UserAgentUtil.toUserAgentString(applicationId, BLOB_CLIENT_NAME, BLOB_CLIENT_VERSION, userAgentConfiguration); Matcher matcher = pattern.matcher(userAgent); String version = encryptionVersion == EncryptionVersion.V2 ? "2.0" : "1.0"; String stringToAppend = "azstorage-clientsideencryption/" + version; if (matcher.matches() && !userAgent.contains(stringToAppend)) { String segment1 = matcher.group(1) == null ? "" : matcher.group(1); String segment2 = matcher.group(2) == null ? "" : matcher.group(2); String segment3 = matcher.group(3) == null ? "" : matcher.group(3); userAgent = segment1 + stringToAppend + " " + segment2 + segment3; } return userAgent; } /** * Sets the encryption key parameters for the client * * @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key * @param keyWrapAlgorithm The {@link String} used to wrap the key. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) { this.keyWrapper = key; this.keyWrapAlgorithm = keyWrapAlgorithm; return this; } /** * Sets the encryption parameters for this client * * @param keyResolver The key resolver used to select the correct key for decrypting existing blobs. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) { this.keyResolver = keyResolver; return this; } private void checkValidEncryptionParameters() { if (this.keyWrapper == null && this.keyResolver == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null")); } if (this.keyWrapper != null && this.keyWrapAlgorithm == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Key Wrap Algorithm must be specified with a Key.")); } } /** * Sets the {@link StorageSharedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link StorageSharedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ public EncryptedBlobClientBuilder credential(StorageSharedKeyCredential credential) { this.storageSharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.tokenCredential = null; this.sasToken = null; return this; } /** * Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link AzureNamedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); return credential(StorageSharedKeyCredential.fromAzureNamedKeyCredential(credential)); } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential {@link TokenCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.storageSharedKeyCredential = null; this.sasToken = null; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. This string should only be the query parameters * (with or without a leading '?') and not a full url. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public EncryptedBlobClientBuilder sasToken(String sasToken) { this.sasToken = Objects.requireNonNull(sasToken, "'sasToken' cannot be null."); this.storageSharedKeyCredential = null; this.tokenCredential = null; return this; } /** * Sets the {@link AzureSasCredential} used to authorize requests sent to the service. * * @param credential {@link AzureSasCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureSasCredential credential) { this.azureSasCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Clears the credential used to authorize the request. * * <p>This is for blobs that are publicly accessible.</p> * * @return the updated EncryptedBlobClientBuilder */ public EncryptedBlobClientBuilder setAnonymousAccess() { this.storageSharedKeyCredential = null; this.tokenCredential = null; this.azureSasCredential = null; this.sasToken = null; return this; } /** * Sets the connection string to connect to the service. * * @param connectionString Connection string of the storage account. * @return the updated EncryptedBlobClientBuilder * @throws IllegalArgumentException If {@code connectionString} is invalid. */ @Override public EncryptedBlobClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, LOGGER); StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint(); if (endpoint == null || endpoint.getPrimaryUri() == null) { throw LOGGER .logExceptionAsError(new IllegalArgumentException( "connectionString missing required settings to derive blob service endpoint.")); } this.endpoint(endpoint.getPrimaryUri()); if (storageConnectionString.getAccountName() != null) { this.accountName = storageConnectionString.getAccountName(); } StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings(); if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) { this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name) * * <p>If the blob name contains special characters, pass in the url encoded version of the blob name. </p> * * <p>If the endpoint is to a blob in the root container, this method will fail as it will interpret the blob name * as the container name. With only one path element, it is impossible to distinguish between a container name and a * blob in the root container, so it is assumed to be the container name as this is much more common. When working * with blobs in the root container, it is best to set the endpoint to the account url and specify the blob name * separately using the {@link EncryptedBlobClientBuilder * * @param endpoint URL of the service * @return the updated EncryptedBlobClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ @Override public EncryptedBlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobUrlParts parts = BlobUrlParts.parse(url); this.accountName = parts.getAccountName(); this.endpoint = BuilderHelper.getEndpoint(parts); this.containerName = parts.getBlobContainerName() == null ? this.containerName : parts.getBlobContainerName(); this.blobName = parts.getBlobName() == null ? this.blobName : Utility.urlEncode(parts.getBlobName()); this.snapshot = parts.getSnapshot(); this.versionId = parts.getVersionId(); String sasToken = parts.getCommonSasQueryParameters().encode(); if (!CoreUtils.isNullOrEmpty(sasToken)) { this.sasToken(sasToken); } } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed.", ex)); } return this; } /** * Sets the name of the container that contains the blob. * * @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root}, * will be used. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder containerName(String containerName) { this.containerName = containerName; return this; } /** * Sets the name of the blob. * * @param blobName Name of the blob. If the blob name contains special characters, pass in the url encoded version * of the blob name. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code blobName} is {@code null} */ public EncryptedBlobClientBuilder blobName(String blobName) { this.blobName = Utility.urlEncode(Utility.urlDecode(Objects.requireNonNull(blobName, "'blobName' cannot be null."))); return this; } /** * Sets the snapshot identifier of the blob. * * @param snapshot Snapshot identifier for the blob. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Sets the version identifier of the blob. * * @param versionId Version identifier for the blob, pass {@code null} to interact with the latest blob version. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder versionId(String versionId) { this.versionId = versionId; return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param httpClient The {@link HttpClient} to use for requests. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { LOGGER.info("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param pipelinePolicy A {@link HttpPipelinePolicy pipeline policy}. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ @Override public EncryptedBlobClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"); if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(pipelinePolicy); } else { perRetryPolicies.add(pipelinePolicy); } return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code logOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Gets the default Storage allowlist log headers and query parameters. * * @return the default http log options. */ public static HttpLogOptions getDefaultHttpLogOptions() { return BuilderHelper.getDefaultHttpLogOptions(); } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the request retry options for all the requests made through the client. * * Setting this is mutually exclusive with using {@link * * @param retryOptions {@link RequestRetryOptions}. * @return the updated EncryptedBlobClientBuilder object. */ public EncryptedBlobClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * Consider using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder retryOptions(RetryOptions retryOptions) { this.coreRetryOptions = retryOptions; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * The {@link * {@link * not ignored when {@code pipeline} is set. * * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @see HttpClientOptions * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code clientOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the {@link BlobServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder serviceVersion(BlobServiceVersion version) { this.version = version; return this; } /** * Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server. * * @param customerProvidedKey {@link CustomerProvidedKey} * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) { if (customerProvidedKey == null) { this.customerProvidedKey = null; } else { this.customerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return this; } /** * Sets the {@code encryption scope} that is used to encrypt blob contents on the server. * * @param encryptionScope Encryption scope containing the encryption key information. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder encryptionScope(String encryptionScope) { if (encryptionScope == null) { this.encryptionScope = null; } else { this.encryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return this; } /** * Configures the builder based on the passed {@link BlobClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobClient BlobClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobClient(BlobClient blobClient) { Objects.requireNonNull(blobClient); return client(blobClient.getHttpPipeline(), blobClient.getBlobUrl(), blobClient.getServiceVersion()); } /** * Configures the builder based on the passed {@link BlobAsyncClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobAsyncClient BlobAsyncClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobAsyncClient(BlobAsyncClient blobAsyncClient) { Objects.requireNonNull(blobAsyncClient); return client(blobAsyncClient.getHttpPipeline(), blobAsyncClient.getBlobUrl(), blobAsyncClient.getServiceVersion()); } /** * Helper method to transform a regular client into an encrypted client * * @param httpPipeline {@link HttpPipeline} * @param endpoint The endpoint. * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ private EncryptedBlobClientBuilder client(HttpPipeline httpPipeline, String endpoint, BlobServiceVersion version) { this.endpoint(endpoint); this.serviceVersion(version); return this.pipeline(httpPipeline); } /** * Sets the requires encryption option. * * @param requiresEncryption Whether encryption is enforced by this client. Client will throw if data is * downloaded and it is not encrypted. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder requiresEncryption(boolean requiresEncryption) { this.requiresEncryption = requiresEncryption; return this; } }