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
Fixed in the new version.
public void testCreate() { Cluster cluster = null; try { String clusterName = "cluster" + randomPadding(); cluster = redisEnterpriseManager.redisEnterprises() .define(clusterName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.ENTERPRISE_E10).withCapacity(2)) .withIdentity(new ManagedServiceIdentity().withType(ManagedServiceIdentityType.NONE)) .withMinimumTlsVersion(TlsVersion.ONE_TWO) .create(); cluster.refresh(); Assertions.assertEquals(cluster.name(), clusterName); Assertions.assertEquals(cluster.name(), redisEnterpriseManager.redisEnterprises().getById(cluster.id()).name()); Assertions.assertTrue(redisEnterpriseManager.redisEnterprises().list().stream().count() > 0); } finally { if (cluster != null) { redisEnterpriseManager.redisEnterprises().deleteById(cluster.id()); } } }
public void testCreate() { Cluster cluster = null; try { String clusterName = "cluster" + randomPadding(); cluster = redisEnterpriseManager.redisEnterprises() .define(clusterName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.ENTERPRISE_E10).withCapacity(2)) .withIdentity(new ManagedServiceIdentity().withType(ManagedServiceIdentityType.NONE)) .withMinimumTlsVersion(TlsVersion.ONE_TWO) .create(); cluster.refresh(); Assertions.assertEquals(cluster.name(), clusterName); Assertions.assertEquals(cluster.name(), redisEnterpriseManager.redisEnterprises().getById(cluster.id()).name()); Assertions.assertTrue(redisEnterpriseManager.redisEnterprises().list().stream().count() > 0); } finally { if (cluster != null) { redisEnterpriseManager.redisEnterprises().deleteById(cluster.id()); } } }
class RedisEnterpriseManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RedisEnterpriseManager redisEnterpriseManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); redisEnterpriseManager = RedisEnterpriseManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RedisEnterpriseManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RedisEnterpriseManager redisEnterpriseManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); redisEnterpriseManager = RedisEnterpriseManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
keep or remove?
public void createItem() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); logger.info("Testing log"); CosmosItemResponse<InternalObjectNode> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); }
logger.info("Testing log");
public void createItem() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); logger.info("Testing log"); CosmosItemResponse<InternalObjectNode> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); }
class CosmosItemTest extends TestSuiteBase { private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private CosmosClient client; private CosmosContainer container; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosItemTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosItemTest() { assertThat(this.client).isNull(); this.client = getClientBuilder().buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.client).isNotNull(); this.client.close(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_alreadyExists() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); try { container.createItem(properties, new CosmosItemRequestOptions()); } catch (Exception e) { assertThat(e).isInstanceOf(CosmosException.class); assertThat(((CosmosException) e).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createLargeItem() throws Exception { InternalObjectNode docDefinition = getDocumentDefinition(UUID.randomUUID().toString()); int size = (int) (ONE_MB * 1.5); BridgeInternal.setProperty(docDefinition, "largeString", StringUtils.repeat("x", size)); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(docDefinition, new CosmosItemRequestOptions()); validateItemResponse(docDefinition, itemResponse); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createItemWithVeryLargePartitionKey() throws Exception { InternalObjectNode docDefinition = getDocumentDefinition(UUID.randomUUID().toString()); StringBuilder sb = new StringBuilder(); for(int i = 0; i < 100; i++) { sb.append(i).append("x"); } BridgeInternal.setProperty(docDefinition, "mypk", sb.toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(docDefinition, new CosmosItemRequestOptions()); validateItemResponse(docDefinition, itemResponse); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readItemWithVeryLargePartitionKey() throws Exception { InternalObjectNode docDefinition = getDocumentDefinition(UUID.randomUUID().toString()); StringBuilder sb = new StringBuilder(); for(int i = 0; i < 100; i++) { sb.append(i).append("x"); } BridgeInternal.setProperty(docDefinition, "mypk", sb.toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(docDefinition); waitIfNeededForReplicasToCatchUp(getClientBuilder()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse<InternalObjectNode> readResponse = container.readItem(docDefinition.getId(), new PartitionKey(sb.toString()), options, InternalObjectNode.class); validateItemResponse(docDefinition, readResponse); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readItem() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); CosmosItemResponse<InternalObjectNode> readResponse1 = container.readItem(properties.getId(), new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(properties, "mypk")), new CosmosItemRequestOptions(), InternalObjectNode.class); validateItemResponse(properties, readResponse1); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readMany() throws Exception { List<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); Set<String> idSet = new HashSet<>(); int numDocuments = 5; for (int i = 0; i < numDocuments; i++) { InternalObjectNode document = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(document); PartitionKey partitionKey = new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(document, "mypk")); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, document.getId()); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(document.getId()); } FeedResponse<InternalObjectNode> feedResponse = container.readMany(cosmosItemIdentities, InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(numDocuments); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics())).isNotNull(); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics()).size()).isGreaterThan(1); for (int i = 0; i < feedResponse.getResults().size(); i++) { InternalObjectNode fetchedResult = feedResponse.getResults().get(i); assertThat(idSet.contains(fetchedResult.getId())).isTrue(); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithSamePartitionKey() throws Exception { String partitionKeyValue = UUID.randomUUID().toString(); List<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); Set<String> idSet = new HashSet<>(); int numDocuments = 5; for (int i = 0; i < numDocuments; i++) { String documentId = UUID.randomUUID().toString(); ObjectNode document = getDocumentDefinition(documentId, partitionKeyValue); container.createItem(document); PartitionKey partitionKey = new PartitionKey(partitionKeyValue); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, documentId); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(documentId); } FeedResponse<InternalObjectNode> feedResponse = container.readMany(cosmosItemIdentities, InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(numDocuments); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics())).isNotNull(); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics()).size()).isEqualTo(1); for (int i = 0; i < feedResponse.getResults().size(); i++) { InternalObjectNode fetchedResult = feedResponse.getResults().get(i); assertThat(idSet.contains(fetchedResult.getId())).isTrue(); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithPojo() throws Exception { List<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); Set<String> idSet = new HashSet<>(); Set<String> valSet = new HashSet<>(); int numDocuments = 5; for (int i = 0; i < numDocuments; i++) { SampleType document = new SampleType(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString()); container.createItem(document); PartitionKey partitionKey = new PartitionKey(document.getMypk()); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, document.getId()); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(document.getId()); valSet.add(document.getVal()); } FeedResponse<SampleType> feedResponse = container.readMany(cosmosItemIdentities, SampleType.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(numDocuments); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics())).isNotNull(); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics()).size()).isGreaterThanOrEqualTo(1); for (int i = 0; i < feedResponse.getResults().size(); i++) { SampleType fetchedResult = feedResponse.getResults().get(i); assertThat(idSet.contains(fetchedResult.getId())).isTrue(); assertThat(valSet.contains(fetchedResult.getVal())).isTrue(); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithPojoAndSingleTuple() throws Exception { List<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); SampleType document = new SampleType(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString()); container.createItem(document); PartitionKey partitionKey = new PartitionKey(document.getMypk()); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, document.getId()); cosmosItemIdentities.add(cosmosItemIdentity); FeedResponse<SampleType> feedResponse = container.readMany(cosmosItemIdentities, SampleType.class); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(1); SampleType fetchedDocument = feedResponse.getResults().get(0); assertThat(document.getId()).isEqualTo(fetchedDocument.getId()); assertThat(document.getMypk()).isEqualTo(fetchedDocument.getMypk()); assertThat(document.getVal()).isEqualTo(fetchedDocument.getVal()); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithSingleTuple() throws Exception { String partitionKeyValue = UUID.randomUUID().toString(); ArrayList<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); HashSet<String> idSet = new HashSet<String>(); int numDocuments = 5; for (int i = 0; i < numDocuments; i++) { String documentId = UUID.randomUUID().toString(); ObjectNode document = getDocumentDefinition(documentId, partitionKeyValue); container.createItem(document); PartitionKey partitionKey = new PartitionKey(partitionKeyValue); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, documentId); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(documentId); } for (int i = 0; i < numDocuments; i++) { FeedResponse<InternalObjectNode> feedResponse = container.readMany(Arrays.asList(cosmosItemIdentities.get(i)), InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(1); assertThat(idSet.contains(feedResponse.getResults().get(0).getId())).isTrue(); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithManyNonExistentItemIds() throws Exception { String partitionKeyValue = UUID.randomUUID().toString(); ArrayList<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); ArrayList<CosmosItemIdentity> nonExistentCosmosItemIdentities = new ArrayList<>(); HashSet<String> idSet = new HashSet<String>(); int numDocuments = 5; int numNonExistentDocuments = 5; for (int i = 0; i < numNonExistentDocuments; i++) { CosmosItemIdentity nonExistentItemIdentity = new CosmosItemIdentity(new PartitionKey(UUID.randomUUID().toString()), UUID.randomUUID().toString()); nonExistentCosmosItemIdentities.add(nonExistentItemIdentity); } for (int i = 0; i < numDocuments; i++) { String documentId = UUID.randomUUID().toString(); ObjectNode document = getDocumentDefinition(documentId, partitionKeyValue); container.createItem(document); PartitionKey partitionKey = new PartitionKey(partitionKeyValue); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, documentId); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(documentId); } cosmosItemIdentities.addAll(nonExistentCosmosItemIdentities); FeedResponse<InternalObjectNode> feedResponse = container.readMany(cosmosItemIdentities, InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(numDocuments); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithFaultyPointRead() throws JsonProcessingException { int numDocuments = 25; List<FeedRange> feedRanges = container.getFeedRanges(); assertThat(feedRanges.size()).isGreaterThanOrEqualTo(2); for (int i = 0; i < numDocuments; i++) { String partitionKeyValue = UUID.randomUUID().toString(); String documentId = UUID.randomUUID().toString(); ObjectNode document = getDocumentDefinition(documentId, partitionKeyValue); container.createItem(document); } SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("SELECT * from c"); stringBuilder.append(" OFFSET 0"); stringBuilder.append(" LIMIT 1"); sqlQuerySpec.setQueryText(stringBuilder.toString()); AtomicReference<String> itemId1 = new AtomicReference<>(""); AtomicReference<String> pkValItem1 = new AtomicReference<>(""); CosmosQueryRequestOptions cosmosQueryRequestOptions1 = new CosmosQueryRequestOptions(); cosmosQueryRequestOptions1.setFeedRange(feedRanges.get(0)); container .queryItems(sqlQuerySpec, cosmosQueryRequestOptions1, InternalObjectNode.class) .iterableByPage() .forEach(response -> { List<InternalObjectNode> results = response.getResults(); assertThat(results).isNotNull(); assertThat(results).isNotEmpty(); assertThat(results.size()).isEqualTo(1); itemId1.set(results.get(0).getId()); pkValItem1.set(results.get(0).getString("mypk")); }); AtomicReference<String> pkValItem2 = new AtomicReference<>(""); CosmosQueryRequestOptions cosmosQueryRequestOptions2 = new CosmosQueryRequestOptions(); cosmosQueryRequestOptions2.setFeedRange(feedRanges.get(1)); container .queryItems(sqlQuerySpec, cosmosQueryRequestOptions2, InternalObjectNode.class) .iterableByPage() .forEach(response -> { List<InternalObjectNode> results = response.getResults(); assertThat(results).isNotNull(); assertThat(results).isNotEmpty(); assertThat(results.size()).isEqualTo(1); pkValItem2.set(results.get(0).getString("mypk")); }); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(new PartitionKey(pkValItem1.get()), itemId1.get()); CosmosItemIdentity nonExistentCosmosItemIdentity = new CosmosItemIdentity(new PartitionKey(pkValItem2.get()), UUID.randomUUID().toString()); List<CosmosItemIdentity> cosmosItemIdentities = Arrays.asList(cosmosItemIdentity, nonExistentCosmosItemIdentity); FeedResponse<InternalObjectNode> feedResponse = container.readMany(cosmosItemIdentities, InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isLessThanOrEqualTo(1); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyOptimizationRequestChargeComparisonForSingleTupleWithSmallSize() throws Exception { String idAndPkValue = UUID.randomUUID().toString(); ObjectNode doc = getDocumentDefinition(idAndPkValue, idAndPkValue); container.createItem(doc); String query = String.format("SELECT * from c where c.id = '%s'", idAndPkValue); CosmosPagedIterable<ObjectNode> queryResult = container.queryItems(query, new CosmosQueryRequestOptions(), ObjectNode.class); FeedResponse<ObjectNode> readManyResult = container.readMany(Arrays.asList(new CosmosItemIdentity(new PartitionKey(idAndPkValue), idAndPkValue)), ObjectNode.class); AtomicReference<Double> queryRequestCharge = new AtomicReference<>(0d); double readManyRequestCharge = 0d; assertThat(queryResult).isNotNull(); assertThat(queryResult.stream().count()).isEqualTo(1L); assertThat(readManyResult).isNotNull(); assertThat(readManyResult.getRequestCharge()).isGreaterThan(0D); queryResult .iterableByPage(1) .forEach(feedResponse -> queryRequestCharge.updateAndGet(v -> v + feedResponse.getRequestCharge())); readManyRequestCharge += readManyResult.getRequestCharge(); assertThat(readManyRequestCharge).isLessThan(queryRequestCharge.get()); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItemWithDuplicateJsonProperties() throws Exception { String id = UUID.randomUUID().toString(); String rawJson = String.format( "{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"property1\": \"5\", " + "\"property1\": \"7\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}", id, id); container.createItem( rawJson.getBytes(StandardCharsets.UTF_8), new PartitionKey(id), new CosmosItemRequestOptions()); Utils.configureSimpleObjectMapper(true); try { CosmosPagedIterable<ObjectNode> pagedIterable = container.queryItems ( "SELECT * FROM c WHERE c.id = '" + id + "'", new CosmosQueryRequestOptions(), ObjectNode.class); List<ObjectNode> items = pagedIterable.stream().collect(Collectors.toList()); assertThat(items).hasSize(1); assertThat(items.get(0).get("property1").asText()).isEqualTo("7"); } finally { Utils.configureSimpleObjectMapper(false); container.deleteItem(id, new PartitionKey(id), new CosmosItemRequestOptions()); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readItemWithSoftTimeoutAndFallback() throws Exception { String pk = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(id, pk); ObjectNode fallBackProperties = getDocumentDefinition("justFallback", "justFallback"); container.createItem(properties); String successfulResponse = wrapWithSoftTimeoutAndFallback( container .asyncContainer .readItem(id, new PartitionKey(pk), new CosmosItemRequestOptions(), ObjectNode.class), Duration.ofDays(3), fallBackProperties) .map(node -> node.get("id").asText()) .block(); assertThat(successfulResponse).isEqualTo(id); String timedOutResponse = wrapWithSoftTimeoutAndFallback( container .asyncContainer .readItem(id, new PartitionKey(pk), new CosmosItemRequestOptions(), ObjectNode.class), Duration.ofNanos(10), fallBackProperties) .map(node -> node.get("id").asText()) .block(); assertThat(timedOutResponse).isEqualTo("justFallback"); Thread.sleep(1000); } static <T> Mono<T> wrapWithSoftTimeoutAndFallback( Mono<CosmosItemResponse<T>> source, Duration softTimeout, T fallback) { AtomicBoolean timeoutElapsed = new AtomicBoolean(false); return Mono .<T>create(sink -> { source .subscribeOn(Schedulers.boundedElastic()) .subscribe( response -> { if (timeoutElapsed.get()) { logger.warn( "COMPLETED SUCCESSFULLY after timeout elapsed. Diagnostics: {}", response.getDiagnostics().toString()); } else { logger.info("COMPLETED SUCCESSFULLY"); } sink.success(response.getItem()); }, error -> { final Throwable unwrappedException = Exceptions.unwrap(error); if (unwrappedException instanceof CosmosException) { final CosmosException cosmosException = (CosmosException) unwrappedException; logger.error( "COMPLETED WITH COSMOS FAILURE. Diagnostics: {}", cosmosException.getDiagnostics() != null ? cosmosException.getDiagnostics().toString() : "n/a", cosmosException); } else { logger.error("COMPLETED WITH GENERIC FAILURE", error); } if (timeoutElapsed.get()) { sink.success(); } else { sink.error(error); } } ); }) .timeout(softTimeout) .onErrorResume(error -> { timeoutElapsed.set(true); return Mono.just(fallback); }); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readItemWithEventualConsistency() throws Exception { CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); String idAndPkValue = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(idAndPkValue, idAndPkValue); CosmosItemResponse<ObjectNode> itemResponse = container.createItem(properties); CosmosItemResponse<ObjectNode> readResponse1 = container.readItem( idAndPkValue, new PartitionKey(idAndPkValue), new CosmosItemRequestOptions() .setSessionToken(StringUtils.repeat("SomeManualInvalidSessionToken", 2000)) .setConsistencyLevel(ConsistencyLevel.EVENTUAL), ObjectNode.class); logger.info("REQUEST DIAGNOSTICS: {}", readResponse1.getDiagnostics().toString()); validateIdOfItemResponse(idAndPkValue, readResponse1); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void replaceItem() throws Exception{ InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); validateItemResponse(properties, itemResponse); String newPropValue = UUID.randomUUID().toString(); BridgeInternal.setProperty(properties, "newProp", newPropValue); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(options, new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(properties, "mypk"))); CosmosItemResponse<InternalObjectNode> replace = container.replaceItem(properties, properties.getId(), new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(properties, "mypk")), options); assertThat(ModelBridgeInternal.getObjectFromJsonSerializable(BridgeInternal.getProperties(replace), "newProp")).isEqualTo(newPropValue); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteItem() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse<?> deleteResponse = container.deleteItem(properties.getId(), new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(properties, "mypk")), options); assertThat(deleteResponse.getStatusCode()).isEqualTo(204); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteItemUsingEntity() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse<?> deleteResponse = container.deleteItem(itemResponse.getItem(), options); assertThat(deleteResponse.getStatusCode()).isEqualTo(204); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItems() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItems() throws Exception{ InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container.queryItems(querySpec, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void distinctQueryItems() throws Exception{ for (int i = 0; i < 10; i++) { container.createItem( getDocumentDefinition(UUID.randomUUID().toString(), "somePartitionKey") ); } String query = "SELECT DISTINCT c.mypk from c"; CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<PartitionKeyWrapper> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, PartitionKeyWrapper.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); long totalRecordCount = feedResponseIterator1.stream().count(); assertThat(totalRecordCount == 1L); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItemsWithCustomCorrelationActivityId() throws Exception{ InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); UUID correlationId = UUID.randomUUID(); ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .setCorrelationActivityId(cosmosQueryRequestOptions, correlationId); CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); feedResponseIterator1 .iterableByPage() .forEach(response -> { assertThat(response.getCorrelationActivityId() == correlationId) .withFailMessage("response.getCorrelationActivityId"); assertThat(response.getCosmosDiagnostics().toString().contains(correlationId.toString())) .withFailMessage("response.getCosmosDiagnostics"); }); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItemsWithEventualConsistency() throws Exception{ CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); String idAndPkValue = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(idAndPkValue, idAndPkValue); CosmosItemResponse<ObjectNode> itemResponse = container.createItem(properties); String query = String.format("SELECT * from c where c.id = '%s'", idAndPkValue); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions() .setSessionToken(StringUtils.repeat("SomeManualInvalidSessionToken", 2000)) .setConsistencyLevel(ConsistencyLevel.EVENTUAL); CosmosPagedIterable<ObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, ObjectNode.class); feedResponseIterator1.handle( (r) -> logger.info("Query RequestDiagnostics: {}", r.getCosmosDiagnostics().toString())); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); assertThat(feedResponseIterator1.stream().count() == 1); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedIterable<ObjectNode> feedResponseIterator3 = container.queryItems(querySpec, cosmosQueryRequestOptions, ObjectNode.class); feedResponseIterator3.handle( (r) -> logger.info("Query RequestDiagnostics: {}", r.getCosmosDiagnostics().toString())); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); assertThat(feedResponseIterator3.stream().count() == 1); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItemsWithContinuationTokenAndPageSize() throws Exception{ List<String> actualIds = new ArrayList<>(); InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); String query = String.format("SELECT * from c where c.id in ('%s', '%s', '%s')", actualIds.get(0), actualIds.get(1), actualIds.get(2)); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); String continuationToken = null; int pageSize = 1; int initialDocumentCount = 3; int finalDocumentCount = 0; CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, InternalObjectNode.class); do { Iterable<FeedResponse<InternalObjectNode>> feedResponseIterable = feedResponseIterator1.iterableByPage(continuationToken, pageSize); for (FeedResponse<InternalObjectNode> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while(continuationToken != null); assertThat(finalDocumentCount).isEqualTo(initialDocumentCount); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsOfLogicalPartition() throws Exception{ String pkValue = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString(), pkValue); CosmosItemResponse<ObjectNode> itemResponse = container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<ObjectNode> feedResponseIterator1 = container.readAllItems( new PartitionKey(pkValue), cosmosQueryRequestOptions, ObjectNode.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); CosmosPagedIterable<ObjectNode> feedResponseIterator3 = container.readAllItems( new PartitionKey(pkValue), cosmosQueryRequestOptions, ObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsOfLogicalPartitionWithContinuationTokenAndPageSize() throws Exception{ String pkValue = UUID.randomUUID().toString(); List<String> actualIds = new ArrayList<>(); ObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString(), pkValue); container.createItem(properties); properties = getDocumentDefinition(UUID.randomUUID().toString(), pkValue); container.createItem(properties); properties = getDocumentDefinition(UUID.randomUUID().toString(), pkValue); container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); String continuationToken = null; int pageSize = 1; int initialDocumentCount = 3; int finalDocumentCount = 0; CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.readAllItems( new PartitionKey(pkValue), cosmosQueryRequestOptions, InternalObjectNode.class); do { Iterable<FeedResponse<InternalObjectNode>> feedResponseIterable = feedResponseIterator1.iterableByPage(continuationToken, pageSize); for (FeedResponse<InternalObjectNode> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while(continuationToken != null); assertThat(finalDocumentCount).isEqualTo(initialDocumentCount); } private InternalObjectNode getDocumentDefinition(String documentId) { final String uuid = UUID.randomUUID().toString(); final InternalObjectNode properties = new InternalObjectNode(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, uuid)); return properties; } private ObjectNode getDocumentDefinition(String documentId, String pkId) throws JsonProcessingException { String json = String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, pkId); return OBJECT_MAPPER.readValue(json, ObjectNode.class); } private void validateItemResponse(InternalObjectNode containerProperties, CosmosItemResponse<InternalObjectNode> createResponse) { assertThat(BridgeInternal.getProperties(createResponse).getId()).isNotNull(); assertThat(BridgeInternal.getProperties(createResponse).getId()) .as("check Resource Id") .isEqualTo(containerProperties.getId()); } private void validateIdOfItemResponse(String expectedId, CosmosItemResponse<ObjectNode> createResponse) { assertThat(BridgeInternal.getProperties(createResponse).getId()).isNotNull(); assertThat(BridgeInternal.getProperties(createResponse).getId()) .as("check Resource Id") .isEqualTo(expectedId); } private static class PartitionKeyWrapper { private String mypk; public PartitionKeyWrapper() { } public String getMypk() { return mypk; } public void setMypk(String mypk) { this.mypk = mypk; } } private static class SampleType { private String id; private String val; private String mypk; public SampleType() { } SampleType(String id, String val, String mypk) { this.id = id; this.val = val; this.mypk = mypk; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getMypk() { return this.mypk; } public void setMypk(String mypk) { this.mypk = mypk; } public void setVal(String val) { this.val = val; } public String getVal() { return this.val; } } }
class CosmosItemTest extends TestSuiteBase { private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private CosmosClient client; private CosmosContainer container; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosItemTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosItemTest() { assertThat(this.client).isNull(); this.client = getClientBuilder().buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.client).isNotNull(); this.client.close(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_alreadyExists() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); try { container.createItem(properties, new CosmosItemRequestOptions()); } catch (Exception e) { assertThat(e).isInstanceOf(CosmosException.class); assertThat(((CosmosException) e).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createLargeItem() throws Exception { InternalObjectNode docDefinition = getDocumentDefinition(UUID.randomUUID().toString()); int size = (int) (ONE_MB * 1.5); BridgeInternal.setProperty(docDefinition, "largeString", StringUtils.repeat("x", size)); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(docDefinition, new CosmosItemRequestOptions()); validateItemResponse(docDefinition, itemResponse); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createItemWithVeryLargePartitionKey() throws Exception { InternalObjectNode docDefinition = getDocumentDefinition(UUID.randomUUID().toString()); StringBuilder sb = new StringBuilder(); for(int i = 0; i < 100; i++) { sb.append(i).append("x"); } BridgeInternal.setProperty(docDefinition, "mypk", sb.toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(docDefinition, new CosmosItemRequestOptions()); validateItemResponse(docDefinition, itemResponse); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readItemWithVeryLargePartitionKey() throws Exception { InternalObjectNode docDefinition = getDocumentDefinition(UUID.randomUUID().toString()); StringBuilder sb = new StringBuilder(); for(int i = 0; i < 100; i++) { sb.append(i).append("x"); } BridgeInternal.setProperty(docDefinition, "mypk", sb.toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(docDefinition); waitIfNeededForReplicasToCatchUp(getClientBuilder()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse<InternalObjectNode> readResponse = container.readItem(docDefinition.getId(), new PartitionKey(sb.toString()), options, InternalObjectNode.class); validateItemResponse(docDefinition, readResponse); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readItem() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); CosmosItemResponse<InternalObjectNode> readResponse1 = container.readItem(properties.getId(), new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(properties, "mypk")), new CosmosItemRequestOptions(), InternalObjectNode.class); validateItemResponse(properties, readResponse1); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readMany() throws Exception { List<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); Set<String> idSet = new HashSet<>(); int numDocuments = 5; for (int i = 0; i < numDocuments; i++) { InternalObjectNode document = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(document); PartitionKey partitionKey = new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(document, "mypk")); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, document.getId()); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(document.getId()); } FeedResponse<InternalObjectNode> feedResponse = container.readMany(cosmosItemIdentities, InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(numDocuments); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics())).isNotNull(); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics()).size()).isGreaterThan(1); for (int i = 0; i < feedResponse.getResults().size(); i++) { InternalObjectNode fetchedResult = feedResponse.getResults().get(i); assertThat(idSet.contains(fetchedResult.getId())).isTrue(); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithSamePartitionKey() throws Exception { String partitionKeyValue = UUID.randomUUID().toString(); List<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); Set<String> idSet = new HashSet<>(); int numDocuments = 5; for (int i = 0; i < numDocuments; i++) { String documentId = UUID.randomUUID().toString(); ObjectNode document = getDocumentDefinition(documentId, partitionKeyValue); container.createItem(document); PartitionKey partitionKey = new PartitionKey(partitionKeyValue); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, documentId); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(documentId); } FeedResponse<InternalObjectNode> feedResponse = container.readMany(cosmosItemIdentities, InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(numDocuments); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics())).isNotNull(); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics()).size()).isEqualTo(1); for (int i = 0; i < feedResponse.getResults().size(); i++) { InternalObjectNode fetchedResult = feedResponse.getResults().get(i); assertThat(idSet.contains(fetchedResult.getId())).isTrue(); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithPojo() throws Exception { List<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); Set<String> idSet = new HashSet<>(); Set<String> valSet = new HashSet<>(); int numDocuments = 5; for (int i = 0; i < numDocuments; i++) { SampleType document = new SampleType(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString()); container.createItem(document); PartitionKey partitionKey = new PartitionKey(document.getMypk()); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, document.getId()); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(document.getId()); valSet.add(document.getVal()); } FeedResponse<SampleType> feedResponse = container.readMany(cosmosItemIdentities, SampleType.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(numDocuments); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics())).isNotNull(); assertThat(diagnosticsAccessor.getClientSideRequestStatistics(feedResponse.getCosmosDiagnostics()).size()).isGreaterThanOrEqualTo(1); for (int i = 0; i < feedResponse.getResults().size(); i++) { SampleType fetchedResult = feedResponse.getResults().get(i); assertThat(idSet.contains(fetchedResult.getId())).isTrue(); assertThat(valSet.contains(fetchedResult.getVal())).isTrue(); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithPojoAndSingleTuple() throws Exception { List<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); SampleType document = new SampleType(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString()); container.createItem(document); PartitionKey partitionKey = new PartitionKey(document.getMypk()); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, document.getId()); cosmosItemIdentities.add(cosmosItemIdentity); FeedResponse<SampleType> feedResponse = container.readMany(cosmosItemIdentities, SampleType.class); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(1); SampleType fetchedDocument = feedResponse.getResults().get(0); assertThat(document.getId()).isEqualTo(fetchedDocument.getId()); assertThat(document.getMypk()).isEqualTo(fetchedDocument.getMypk()); assertThat(document.getVal()).isEqualTo(fetchedDocument.getVal()); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithSingleTuple() throws Exception { String partitionKeyValue = UUID.randomUUID().toString(); ArrayList<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); HashSet<String> idSet = new HashSet<String>(); int numDocuments = 5; for (int i = 0; i < numDocuments; i++) { String documentId = UUID.randomUUID().toString(); ObjectNode document = getDocumentDefinition(documentId, partitionKeyValue); container.createItem(document); PartitionKey partitionKey = new PartitionKey(partitionKeyValue); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, documentId); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(documentId); } for (int i = 0; i < numDocuments; i++) { FeedResponse<InternalObjectNode> feedResponse = container.readMany(Arrays.asList(cosmosItemIdentities.get(i)), InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(1); assertThat(idSet.contains(feedResponse.getResults().get(0).getId())).isTrue(); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithManyNonExistentItemIds() throws Exception { String partitionKeyValue = UUID.randomUUID().toString(); ArrayList<CosmosItemIdentity> cosmosItemIdentities = new ArrayList<>(); ArrayList<CosmosItemIdentity> nonExistentCosmosItemIdentities = new ArrayList<>(); HashSet<String> idSet = new HashSet<String>(); int numDocuments = 5; int numNonExistentDocuments = 5; for (int i = 0; i < numNonExistentDocuments; i++) { CosmosItemIdentity nonExistentItemIdentity = new CosmosItemIdentity(new PartitionKey(UUID.randomUUID().toString()), UUID.randomUUID().toString()); nonExistentCosmosItemIdentities.add(nonExistentItemIdentity); } for (int i = 0; i < numDocuments; i++) { String documentId = UUID.randomUUID().toString(); ObjectNode document = getDocumentDefinition(documentId, partitionKeyValue); container.createItem(document); PartitionKey partitionKey = new PartitionKey(partitionKeyValue); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(partitionKey, documentId); cosmosItemIdentities.add(cosmosItemIdentity); idSet.add(documentId); } cosmosItemIdentities.addAll(nonExistentCosmosItemIdentities); FeedResponse<InternalObjectNode> feedResponse = container.readMany(cosmosItemIdentities, InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isEqualTo(numDocuments); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyWithFaultyPointRead() throws JsonProcessingException { int numDocuments = 25; List<FeedRange> feedRanges = container.getFeedRanges(); assertThat(feedRanges.size()).isGreaterThanOrEqualTo(2); for (int i = 0; i < numDocuments; i++) { String partitionKeyValue = UUID.randomUUID().toString(); String documentId = UUID.randomUUID().toString(); ObjectNode document = getDocumentDefinition(documentId, partitionKeyValue); container.createItem(document); } SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("SELECT * from c"); stringBuilder.append(" OFFSET 0"); stringBuilder.append(" LIMIT 1"); sqlQuerySpec.setQueryText(stringBuilder.toString()); AtomicReference<String> itemId1 = new AtomicReference<>(""); AtomicReference<String> pkValItem1 = new AtomicReference<>(""); CosmosQueryRequestOptions cosmosQueryRequestOptions1 = new CosmosQueryRequestOptions(); cosmosQueryRequestOptions1.setFeedRange(feedRanges.get(0)); container .queryItems(sqlQuerySpec, cosmosQueryRequestOptions1, InternalObjectNode.class) .iterableByPage() .forEach(response -> { List<InternalObjectNode> results = response.getResults(); assertThat(results).isNotNull(); assertThat(results).isNotEmpty(); assertThat(results.size()).isEqualTo(1); itemId1.set(results.get(0).getId()); pkValItem1.set(results.get(0).getString("mypk")); }); AtomicReference<String> pkValItem2 = new AtomicReference<>(""); CosmosQueryRequestOptions cosmosQueryRequestOptions2 = new CosmosQueryRequestOptions(); cosmosQueryRequestOptions2.setFeedRange(feedRanges.get(1)); container .queryItems(sqlQuerySpec, cosmosQueryRequestOptions2, InternalObjectNode.class) .iterableByPage() .forEach(response -> { List<InternalObjectNode> results = response.getResults(); assertThat(results).isNotNull(); assertThat(results).isNotEmpty(); assertThat(results.size()).isEqualTo(1); pkValItem2.set(results.get(0).getString("mypk")); }); CosmosItemIdentity cosmosItemIdentity = new CosmosItemIdentity(new PartitionKey(pkValItem1.get()), itemId1.get()); CosmosItemIdentity nonExistentCosmosItemIdentity = new CosmosItemIdentity(new PartitionKey(pkValItem2.get()), UUID.randomUUID().toString()); List<CosmosItemIdentity> cosmosItemIdentities = Arrays.asList(cosmosItemIdentity, nonExistentCosmosItemIdentity); FeedResponse<InternalObjectNode> feedResponse = container.readMany(cosmosItemIdentities, InternalObjectNode.class); assertThat(feedResponse).isNotNull(); assertThat(feedResponse.getResults()).isNotNull(); assertThat(feedResponse.getResults().size()).isLessThanOrEqualTo(1); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readManyOptimizationRequestChargeComparisonForSingleTupleWithSmallSize() throws Exception { String idAndPkValue = UUID.randomUUID().toString(); ObjectNode doc = getDocumentDefinition(idAndPkValue, idAndPkValue); container.createItem(doc); String query = String.format("SELECT * from c where c.id = '%s'", idAndPkValue); CosmosPagedIterable<ObjectNode> queryResult = container.queryItems(query, new CosmosQueryRequestOptions(), ObjectNode.class); FeedResponse<ObjectNode> readManyResult = container.readMany(Arrays.asList(new CosmosItemIdentity(new PartitionKey(idAndPkValue), idAndPkValue)), ObjectNode.class); AtomicReference<Double> queryRequestCharge = new AtomicReference<>(0d); double readManyRequestCharge = 0d; assertThat(queryResult).isNotNull(); assertThat(queryResult.stream().count()).isEqualTo(1L); assertThat(readManyResult).isNotNull(); assertThat(readManyResult.getRequestCharge()).isGreaterThan(0D); queryResult .iterableByPage(1) .forEach(feedResponse -> queryRequestCharge.updateAndGet(v -> v + feedResponse.getRequestCharge())); readManyRequestCharge += readManyResult.getRequestCharge(); assertThat(readManyRequestCharge).isLessThan(queryRequestCharge.get()); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItemWithDuplicateJsonProperties() throws Exception { String id = UUID.randomUUID().toString(); String rawJson = String.format( "{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"property1\": \"5\", " + "\"property1\": \"7\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}", id, id); container.createItem( rawJson.getBytes(StandardCharsets.UTF_8), new PartitionKey(id), new CosmosItemRequestOptions()); Utils.configureSimpleObjectMapper(true); try { CosmosPagedIterable<ObjectNode> pagedIterable = container.queryItems ( "SELECT * FROM c WHERE c.id = '" + id + "'", new CosmosQueryRequestOptions(), ObjectNode.class); List<ObjectNode> items = pagedIterable.stream().collect(Collectors.toList()); assertThat(items).hasSize(1); assertThat(items.get(0).get("property1").asText()).isEqualTo("7"); } finally { Utils.configureSimpleObjectMapper(false); container.deleteItem(id, new PartitionKey(id), new CosmosItemRequestOptions()); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readItemWithSoftTimeoutAndFallback() throws Exception { String pk = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(id, pk); ObjectNode fallBackProperties = getDocumentDefinition("justFallback", "justFallback"); container.createItem(properties); String successfulResponse = wrapWithSoftTimeoutAndFallback( container .asyncContainer .readItem(id, new PartitionKey(pk), new CosmosItemRequestOptions(), ObjectNode.class), Duration.ofDays(3), fallBackProperties) .map(node -> node.get("id").asText()) .block(); assertThat(successfulResponse).isEqualTo(id); String timedOutResponse = wrapWithSoftTimeoutAndFallback( container .asyncContainer .readItem(id, new PartitionKey(pk), new CosmosItemRequestOptions(), ObjectNode.class), Duration.ofNanos(10), fallBackProperties) .map(node -> node.get("id").asText()) .block(); assertThat(timedOutResponse).isEqualTo("justFallback"); Thread.sleep(1000); } static <T> Mono<T> wrapWithSoftTimeoutAndFallback( Mono<CosmosItemResponse<T>> source, Duration softTimeout, T fallback) { AtomicBoolean timeoutElapsed = new AtomicBoolean(false); return Mono .<T>create(sink -> { source .subscribeOn(Schedulers.boundedElastic()) .subscribe( response -> { if (timeoutElapsed.get()) { logger.warn( "COMPLETED SUCCESSFULLY after timeout elapsed. Diagnostics: {}", response.getDiagnostics().toString()); } else { logger.info("COMPLETED SUCCESSFULLY"); } sink.success(response.getItem()); }, error -> { final Throwable unwrappedException = Exceptions.unwrap(error); if (unwrappedException instanceof CosmosException) { final CosmosException cosmosException = (CosmosException) unwrappedException; logger.error( "COMPLETED WITH COSMOS FAILURE. Diagnostics: {}", cosmosException.getDiagnostics() != null ? cosmosException.getDiagnostics().toString() : "n/a", cosmosException); } else { logger.error("COMPLETED WITH GENERIC FAILURE", error); } if (timeoutElapsed.get()) { sink.success(); } else { sink.error(error); } } ); }) .timeout(softTimeout) .onErrorResume(error -> { timeoutElapsed.set(true); return Mono.just(fallback); }); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readItemWithEventualConsistency() throws Exception { CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); String idAndPkValue = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(idAndPkValue, idAndPkValue); CosmosItemResponse<ObjectNode> itemResponse = container.createItem(properties); CosmosItemResponse<ObjectNode> readResponse1 = container.readItem( idAndPkValue, new PartitionKey(idAndPkValue), new CosmosItemRequestOptions() .setSessionToken(StringUtils.repeat("SomeManualInvalidSessionToken", 2000)) .setConsistencyLevel(ConsistencyLevel.EVENTUAL), ObjectNode.class); logger.info("REQUEST DIAGNOSTICS: {}", readResponse1.getDiagnostics().toString()); validateIdOfItemResponse(idAndPkValue, readResponse1); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void replaceItem() throws Exception{ InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); validateItemResponse(properties, itemResponse); String newPropValue = UUID.randomUUID().toString(); BridgeInternal.setProperty(properties, "newProp", newPropValue); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(options, new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(properties, "mypk"))); CosmosItemResponse<InternalObjectNode> replace = container.replaceItem(properties, properties.getId(), new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(properties, "mypk")), options); assertThat(ModelBridgeInternal.getObjectFromJsonSerializable(BridgeInternal.getProperties(replace), "newProp")).isEqualTo(newPropValue); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteItem() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse<?> deleteResponse = container.deleteItem(properties.getId(), new PartitionKey(ModelBridgeInternal.getObjectFromJsonSerializable(properties, "mypk")), options); assertThat(deleteResponse.getStatusCode()).isEqualTo(204); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteItemUsingEntity() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse<?> deleteResponse = container.deleteItem(itemResponse.getItem(), options); assertThat(deleteResponse.getStatusCode()).isEqualTo(204); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItems() throws Exception { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItems() throws Exception{ InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container.queryItems(querySpec, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void distinctQueryItems() throws Exception{ for (int i = 0; i < 10; i++) { container.createItem( getDocumentDefinition(UUID.randomUUID().toString(), "somePartitionKey") ); } String query = "SELECT DISTINCT c.mypk from c"; CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<PartitionKeyWrapper> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, PartitionKeyWrapper.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); long totalRecordCount = feedResponseIterator1.stream().count(); assertThat(totalRecordCount == 1L); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItemsWithCustomCorrelationActivityId() throws Exception{ InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); UUID correlationId = UUID.randomUUID(); ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .setCorrelationActivityId(cosmosQueryRequestOptions, correlationId); CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); feedResponseIterator1 .iterableByPage() .forEach(response -> { assertThat(response.getCorrelationActivityId() == correlationId) .withFailMessage("response.getCorrelationActivityId"); assertThat(response.getCosmosDiagnostics().toString().contains(correlationId.toString())) .withFailMessage("response.getCosmosDiagnostics"); }); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItemsWithEventualConsistency() throws Exception{ CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); String idAndPkValue = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(idAndPkValue, idAndPkValue); CosmosItemResponse<ObjectNode> itemResponse = container.createItem(properties); String query = String.format("SELECT * from c where c.id = '%s'", idAndPkValue); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions() .setSessionToken(StringUtils.repeat("SomeManualInvalidSessionToken", 2000)) .setConsistencyLevel(ConsistencyLevel.EVENTUAL); CosmosPagedIterable<ObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, ObjectNode.class); feedResponseIterator1.handle( (r) -> logger.info("Query RequestDiagnostics: {}", r.getCosmosDiagnostics().toString())); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); assertThat(feedResponseIterator1.stream().count() == 1); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedIterable<ObjectNode> feedResponseIterator3 = container.queryItems(querySpec, cosmosQueryRequestOptions, ObjectNode.class); feedResponseIterator3.handle( (r) -> logger.info("Query RequestDiagnostics: {}", r.getCosmosDiagnostics().toString())); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); assertThat(feedResponseIterator3.stream().count() == 1); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItemsWithContinuationTokenAndPageSize() throws Exception{ List<String> actualIds = new ArrayList<>(); InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); String query = String.format("SELECT * from c where c.id in ('%s', '%s', '%s')", actualIds.get(0), actualIds.get(1), actualIds.get(2)); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); String continuationToken = null; int pageSize = 1; int initialDocumentCount = 3; int finalDocumentCount = 0; CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, InternalObjectNode.class); do { Iterable<FeedResponse<InternalObjectNode>> feedResponseIterable = feedResponseIterator1.iterableByPage(continuationToken, pageSize); for (FeedResponse<InternalObjectNode> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while(continuationToken != null); assertThat(finalDocumentCount).isEqualTo(initialDocumentCount); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsOfLogicalPartition() throws Exception{ String pkValue = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString(), pkValue); CosmosItemResponse<ObjectNode> itemResponse = container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<ObjectNode> feedResponseIterator1 = container.readAllItems( new PartitionKey(pkValue), cosmosQueryRequestOptions, ObjectNode.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); CosmosPagedIterable<ObjectNode> feedResponseIterator3 = container.readAllItems( new PartitionKey(pkValue), cosmosQueryRequestOptions, ObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsOfLogicalPartitionWithContinuationTokenAndPageSize() throws Exception{ String pkValue = UUID.randomUUID().toString(); List<String> actualIds = new ArrayList<>(); ObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString(), pkValue); container.createItem(properties); properties = getDocumentDefinition(UUID.randomUUID().toString(), pkValue); container.createItem(properties); properties = getDocumentDefinition(UUID.randomUUID().toString(), pkValue); container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); String continuationToken = null; int pageSize = 1; int initialDocumentCount = 3; int finalDocumentCount = 0; CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.readAllItems( new PartitionKey(pkValue), cosmosQueryRequestOptions, InternalObjectNode.class); do { Iterable<FeedResponse<InternalObjectNode>> feedResponseIterable = feedResponseIterator1.iterableByPage(continuationToken, pageSize); for (FeedResponse<InternalObjectNode> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while(continuationToken != null); assertThat(finalDocumentCount).isEqualTo(initialDocumentCount); } private InternalObjectNode getDocumentDefinition(String documentId) { final String uuid = UUID.randomUUID().toString(); final InternalObjectNode properties = new InternalObjectNode(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, uuid)); return properties; } private ObjectNode getDocumentDefinition(String documentId, String pkId) throws JsonProcessingException { String json = String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, pkId); return OBJECT_MAPPER.readValue(json, ObjectNode.class); } private void validateItemResponse(InternalObjectNode containerProperties, CosmosItemResponse<InternalObjectNode> createResponse) { assertThat(BridgeInternal.getProperties(createResponse).getId()).isNotNull(); assertThat(BridgeInternal.getProperties(createResponse).getId()) .as("check Resource Id") .isEqualTo(containerProperties.getId()); } private void validateIdOfItemResponse(String expectedId, CosmosItemResponse<ObjectNode> createResponse) { assertThat(BridgeInternal.getProperties(createResponse).getId()).isNotNull(); assertThat(BridgeInternal.getProperties(createResponse).getId()) .as("check Resource Id") .isEqualTo(expectedId); } private static class PartitionKeyWrapper { private String mypk; public PartitionKeyWrapper() { } public String getMypk() { return mypk; } public void setMypk(String mypk) { this.mypk = mypk; } } private static class SampleType { private String id; private String val; private String mypk; public SampleType() { } SampleType(String id, String val, String mypk) { this.id = id; this.val = val; this.mypk = mypk; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getMypk() { return this.mypk; } public void setMypk(String mypk) { this.mypk = mypk; } public void setVal(String val) { this.val = val; } public String getVal() { return this.val; } } }
should this be in a try finally block - just in case somehow we got some failures
public void createWithAutoscale() throws ClassNotFoundException { final CosmosEntityInformation<AutoScaleSample, String> autoScaleSampleInfo = new CosmosEntityInformation<>(AutoScaleSample.class); CosmosContainerProperties containerProperties = cosmosTemplate.createContainerIfNotExists(autoScaleSampleInfo); assertNotNull(containerProperties); ThroughputResponse throughput = client.getDatabase(TestConstants.DB_NAME) .getContainer(autoScaleSampleInfo.getContainerName()) .readThroughput() .block(); assertNotNull(throughput); assertEquals(Integer.parseInt(TestConstants.AUTOSCALE_MAX_THROUGHPUT), throughput.getProperties().getAutoscaleMaxThroughput()); collectionManager.deleteContainer(autoScaleSampleInfo); }
collectionManager.deleteContainer(autoScaleSampleInfo);
public void createWithAutoscale() throws ClassNotFoundException { final CosmosEntityInformation<AutoScaleSample, String> autoScaleSampleInfo = new CosmosEntityInformation<>(AutoScaleSample.class); CosmosContainerProperties containerProperties = cosmosTemplate.createContainerIfNotExists(autoScaleSampleInfo); assertNotNull(containerProperties); ThroughputResponse throughput = client.getDatabase(TestConstants.DB_NAME) .getContainer(autoScaleSampleInfo.getContainerName()) .readThroughput() .block(); assertNotNull(throughput); assertEquals(Integer.parseInt(TestConstants.AUTOSCALE_MAX_THROUGHPUT), throughput.getProperties().getAutoscaleMaxThroughput()); collectionManager.deleteContainer(autoScaleSampleInfo); }
class CosmosTemplateIT { private static final Person TEST_PERSON = new Person(ID_1, FIRST_NAME, LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); private static final Person TEST_PERSON_2 = new Person(ID_2, NEW_FIRST_NAME, NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); private static final Person TEST_PERSON_3 = new Person(ID_3, NEW_FIRST_NAME, NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); private static final BasicItem BASIC_ITEM = new BasicItem(ID_1); private static final String PRECONDITION_IS_NOT_MET = "is not met"; private static final String WRONG_ETAG = "WRONG_ETAG"; private static final String INVALID_ID = "http: private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final JsonNode NEW_PASSPORT_IDS_BY_COUNTRY_JSON = OBJECT_MAPPER.convertValue(NEW_PASSPORT_IDS_BY_COUNTRY, JsonNode.class); private static final CosmosPatchOperations operations = CosmosPatchOperations .create() .replace("/age", PATCH_AGE_1); CosmosPatchOperations multiPatchOperations = CosmosPatchOperations .create() .set("/firstName", PATCH_FIRST_NAME) .replace("/passportIdsByCountry", NEW_PASSPORT_IDS_BY_COUNTRY_JSON) .add("/hobbies/2", PATCH_HOBBY1) .remove("/shippingAddresses/1") .increment("/age", PATCH_AGE_INCREMENT); private static final CosmosPatchItemRequestOptions options = new CosmosPatchItemRequestOptions(); @ClassRule public static final IntegrationTestCollectionManager collectionManager = new IntegrationTestCollectionManager(); private static CosmosAsyncClient client; private static CosmosTemplate cosmosTemplate; private static CosmosEntityInformation<Person, String> personInfo; private static String containerName; private Person insertedPerson; private BasicItem pointReadItem; @Autowired private ApplicationContext applicationContext; @Autowired private CosmosClientBuilder cosmosClientBuilder; @Autowired private CosmosConfig cosmosConfig; @Autowired private ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils; public CosmosTemplateIT() throws JsonProcessingException { } @Before public void setUp() throws ClassNotFoundException { if (cosmosTemplate == null) { client = CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder); personInfo = new CosmosEntityInformation<>(Person.class); containerName = personInfo.getContainerName(); cosmosTemplate = createCosmosTemplate(cosmosConfig, TestConstants.DB_NAME); } collectionManager.ensureContainersCreatedAndEmpty(cosmosTemplate, Person.class, GenIdEntity.class, AuditableEntity.class, BasicItem.class); insertedPerson = cosmosTemplate.insert(Person.class.getSimpleName(), TEST_PERSON, new PartitionKey(TEST_PERSON.getLastName())); pointReadItem = cosmosTemplate.insert(BasicItem.class.getSimpleName(), BASIC_ITEM, new PartitionKey(BASIC_ITEM.getId())); } private CosmosTemplate createCosmosTemplate(CosmosConfig config, String dbName) throws ClassNotFoundException { final CosmosFactory cosmosFactory = new CosmosFactory(client, dbName); final CosmosMappingContext mappingContext = new CosmosMappingContext(); mappingContext.setInitialEntitySet(new EntityScanner(this.applicationContext).scan(Persistent.class)); final MappingCosmosConverter cosmosConverter = new MappingCosmosConverter(mappingContext, null); return new CosmosTemplate(cosmosFactory, config, cosmosConverter); } private void insertPerson(Person person) { cosmosTemplate.insert(person, new PartitionKey(personInfo.getPartitionKeyFieldValue(person))); } @Test public void testInsertDuplicateIdShouldFailWithConflictException() { try { cosmosTemplate.insert(Person.class.getSimpleName(), TEST_PERSON, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); fail(); } catch (CosmosAccessException ex) { assertThat(ex.getCosmosException().getStatusCode()).isEqualTo(TestConstants.CONFLICT_STATUS_CODE); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } } @Test(expected = CosmosAccessException.class) public void testInsertShouldFailIfColumnNotAnnotatedWithAutoGenerate() { final Person person = new Person(null, FIRST_NAME, LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); cosmosTemplate.insert(Person.class.getSimpleName(), person, new PartitionKey(person.getLastName())); } @Test public void testInsertShouldGenerateIdIfColumnAnnotatedWithAutoGenerate() { final GenIdEntity entity = new GenIdEntity(null, "foo"); final GenIdEntity insertedEntity = cosmosTemplate.insert(GenIdEntity.class.getSimpleName(), entity, null); assertThat(insertedEntity.getId()).isNotNull(); } @Test public void testFindAll() { final List<Person> result = TestUtils.toList(cosmosTemplate.findAll(Person.class.getSimpleName(), Person.class)); assertThat(result.size()).isEqualTo(1); assertThat(result.get(0)).isEqualTo(TEST_PERSON); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindByIdPointRead() { final BasicItem result = cosmosTemplate.findById(BasicItem.class.getSimpleName(), BASIC_ITEM.getId(), BasicItem.class); assertEquals(result, BASIC_ITEM); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final BasicItem nullResult = cosmosTemplate.findById(BasicItem.class.getSimpleName(), NOT_EXIST_ID, BasicItem.class); assertThat(nullResult).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics().toString().contains("\"requestOperationType\":\"Read\"")).isTrue(); } @Test public void testFindById() { final Person result = cosmosTemplate.findById(Person.class.getSimpleName(), TEST_PERSON.getId(), Person.class); assertEquals(result, TEST_PERSON); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); final Person nullResult = cosmosTemplate.findById(Person.class.getSimpleName(), NOT_EXIST_ID, Person.class); assertThat(nullResult).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } @Test public void testFindByIdWithInvalidId() { try { cosmosTemplate.findById(BasicItem.class.getSimpleName(), INVALID_ID, BasicItem.class); fail(); } catch (CosmosAccessException ex) { assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } } @Test public void testFindByMultiIds() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); final List<Object> ids = Lists.newArrayList(ID_1, ID_2, ID_3); final List<Person> result = TestUtils.toList(cosmosTemplate.findByIds(ids, Person.class, containerName)); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); final List<Person> expected = Lists.newArrayList(TEST_PERSON, TEST_PERSON_2, TEST_PERSON_3); assertThat(result.size()).isEqualTo(expected.size()); assertThat(result).containsAll(expected); } @Test public void testUpsertNewDocument() { cosmosTemplate.deleteById(Person.class.getSimpleName(), TEST_PERSON.getId(), new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); final String firstName = NEW_FIRST_NAME + "_" + UUID.randomUUID(); final Person newPerson = new Person(TEST_PERSON.getId(), firstName, NEW_FIRST_NAME, null, null, AGE, PASSPORT_IDS_BY_COUNTRY); final Person person = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), newPerson); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); assertEquals(person.getFirstName(), firstName); } @Test public void testUpdateWithReturnEntity() { final Person updated = new Person(TEST_PERSON.getId(), UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses(), AGE, PASSPORT_IDS_BY_COUNTRY); updated.set_etag(insertedPerson.get_etag()); final Person updatedPerson = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), updated); final Person findPersonById = cosmosTemplate.findById(Person.class.getSimpleName(), updatedPerson.getId(), Person.class); assertEquals(updatedPerson, updated); assertThat(updatedPerson.get_etag()).isEqualTo(findPersonById.get_etag()); } @Test public void testUpdate() { final Person updated = new Person(TEST_PERSON.getId(), UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses(), AGE, PASSPORT_IDS_BY_COUNTRY); updated.set_etag(insertedPerson.get_etag()); final Person person = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), updated); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); assertEquals(person, updated); } @Test public void testPatch() { Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, operations); assertEquals(patchedPerson.getAge(), PATCH_AGE_1); } @Test public void testPatchMultiOperations() { Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, multiPatchOperations); assertEquals(patchedPerson.getAge().intValue(), (AGE + PATCH_AGE_INCREMENT)); assertEquals(patchedPerson.getHobbies(), PATCH_HOBBIES); assertEquals(patchedPerson.getFirstName(), PATCH_FIRST_NAME); assertEquals(patchedPerson.getShippingAddresses().size(), 1); assertEquals(patchedPerson.getPassportIdsByCountry(), NEW_PASSPORT_IDS_BY_COUNTRY); } @Test public void testPatchPreConditionSuccess() { options.setFilterPredicate("FROM person p WHERE p.lastName = '"+LAST_NAME+"'"); Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, operations, options); assertEquals(patchedPerson.getAge(), PATCH_AGE_1); } @Test public void testPatchPreConditionFail() { try { options.setFilterPredicate("FROM person p WHERE p.lastName = 'dummy'"); Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, operations, options); assertEquals(patchedPerson.getAge(), PATCH_AGE_1); fail(); } catch (CosmosAccessException ex) { assertThat(ex.getCosmosException().getStatusCode()).isEqualTo(TestConstants.PRECONDITION_FAILED_STATUS_CODE); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } } @Test public void testOptimisticLockWhenUpdatingWithWrongEtag() { final Person updated = new Person(TEST_PERSON.getId(), UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses(), AGE, PASSPORT_IDS_BY_COUNTRY); updated.set_etag(WRONG_ETAG); try { cosmosTemplate.upsert(Person.class.getSimpleName(), updated); } catch (CosmosAccessException e) { assertThat(e.getCosmosException()).isNotNull(); final Throwable cosmosClientException = e.getCosmosException(); assertThat(cosmosClientException).isInstanceOf(CosmosException.class); assertThat(cosmosClientException.getMessage()).contains(PRECONDITION_IS_NOT_MET); assertThat(responseDiagnosticsTestUtils.getDiagnostics()).isNotNull(); final Person unmodifiedPerson = cosmosTemplate.findById(Person.class.getSimpleName(), TEST_PERSON.getId(), Person.class); assertThat(unmodifiedPerson.getFirstName()).isEqualTo(insertedPerson.getFirstName()); return; } fail(); } @Test public void testDeleteById() { cosmosTemplate.insert(TEST_PERSON_2, null); assertThat(cosmosTemplate.count(Person.class.getSimpleName())).isEqualTo(2); cosmosTemplate.deleteById(Person.class.getSimpleName(), TEST_PERSON.getId(), new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final List<Person> result = TestUtils.toList(cosmosTemplate.findAll(Person.class)); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); assertThat(result.size()).isEqualTo(1); assertEquals(result.get(0), TEST_PERSON_2); } @Test public void testDeleteByEntity() { Person insertedPerson = cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(TEST_PERSON_2.getLastName())); assertThat(cosmosTemplate.count(Person.class.getSimpleName())).isEqualTo(2); cosmosTemplate.deleteEntity(Person.class.getSimpleName(), insertedPerson); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final List<Person> result = TestUtils.toList(cosmosTemplate.findAll(Person.class)); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); assertThat(result.size()).isEqualTo(1); assertEquals(result.get(0), TEST_PERSON); } @Test public void testCountByContainer() { final long prevCount = cosmosTemplate.count(containerName); assertThat(prevCount).isEqualTo(1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); final long newCount = cosmosTemplate.count(containerName); assertThat(newCount).isEqualTo(2); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testCountByQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON_2.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = cosmosTemplate.count(query, containerName); assertThat(count).isEqualTo(1); final Criteria criteriaIgnoreCase = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON_2.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); final CosmosQuery queryIgnoreCase = new CosmosQuery(criteriaIgnoreCase); final long countIgnoreCase = cosmosTemplate.count(queryIgnoreCase, containerName); assertThat(countIgnoreCase).isEqualTo(1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindAllPageableMultiPages() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final CosmosPageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_1, null); final Page<Person> page1 = cosmosTemplate.findAll(pageRequest, Person.class, containerName); assertThat(page1.getContent().size()).isEqualTo(PAGE_SIZE_1); PageTestUtils.validateNonLastPage(page1, PAGE_SIZE_1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); final Page<Person> page2 = cosmosTemplate.findAll(page1.nextPageable(), Person.class, containerName); assertThat(page2.getContent().size()).isEqualTo(1); PageTestUtils.validateLastPage(page2, PAGE_SIZE_1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindAllPageableMultiPagesPageSizeTwo() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final CosmosPageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_2, null); final Page<Person> page1 = cosmosTemplate.findAll(pageRequest, Person.class, containerName); final List<Person> resultPage1 = TestUtils.toList(page1); final List<Person> expected = Lists.newArrayList(TEST_PERSON, TEST_PERSON_2); assertThat(resultPage1.size()).isEqualTo(expected.size()); assertThat(resultPage1).containsAll(expected); PageTestUtils.validateNonLastPage(page1, PAGE_SIZE_2); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); final Page<Person> page2 = cosmosTemplate.findAll(page1.nextPageable(), Person.class, containerName); final List<Person> resultPage2 = TestUtils.toList(page2); final List<Person> expected2 = Lists.newArrayList(TEST_PERSON_3); assertThat(resultPage2.size()).isEqualTo(expected2.size()); assertThat(resultPage2).containsAll(expected2); PageTestUtils.validateLastPage(page2, PAGE_SIZE_2); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testPaginationQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(FIRST_NAME), Part.IgnoreCaseType.NEVER); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_2, null); final CosmosQuery query = new CosmosQuery(criteria).with(pageRequest); final Page<Person> page = cosmosTemplate.paginationQuery(query, Person.class, containerName); assertThat(page.getContent().size()).isEqualTo(1); PageTestUtils.validateLastPage(page, PAGE_SIZE_2); final Criteria criteriaIgnoreCase = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(FIRST_NAME.toUpperCase()), Part.IgnoreCaseType.ALWAYS); final CosmosQuery queryIgnoreCase = new CosmosQuery(criteriaIgnoreCase).with(pageRequest); final Page<Person> pageIgnoreCase = cosmosTemplate.paginationQuery(queryIgnoreCase, Person.class, containerName); assertThat(pageIgnoreCase.getContent().size()).isEqualTo(1); PageTestUtils.validateLastPage(pageIgnoreCase, PAGE_SIZE_2); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindWithSortAndLimit() { final Person testPerson4 = new Person("id_4", "fred", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson5 = new Person("id_5", "barney", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson6 = new Person("id_6", "george", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); insertPerson(testPerson4); insertPerson(testPerson5); insertPerson(testPerson6); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "lastName", Collections.singletonList(NEW_LAST_NAME), Part.IgnoreCaseType.ALWAYS); final CosmosQuery query = new CosmosQuery(criteria); query.with(Sort.by(Sort.Direction.ASC, "firstName")); final List<Person> result = TestUtils.toList(cosmosTemplate.find(query, Person.class, containerName)); assertThat(result.size()).isEqualTo(3); assertThat(result.get(0).getFirstName()).isEqualTo("barney"); assertThat(result.get(1).getFirstName()).isEqualTo("fred"); assertThat(result.get(2).getFirstName()).isEqualTo("george"); query.withLimit(1); final List<Person> resultWithLimit = TestUtils.toList(cosmosTemplate.find(query, Person.class, containerName)); assertThat(resultWithLimit.size()).isEqualTo(1); assertThat(resultWithLimit.get(0).getFirstName()).isEqualTo("barney"); } @Test public void testFindWithOffsetAndLimit() { final Person testPerson4 = new Person("id_4", "fred", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson5 = new Person("id_5", "barney", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson6 = new Person("id_6", "george", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); insertPerson(testPerson4); insertPerson(testPerson5); insertPerson(testPerson6); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "lastName", Collections.singletonList(NEW_LAST_NAME), Part.IgnoreCaseType.ALWAYS); final CosmosQuery query = new CosmosQuery(criteria); query.with(Sort.by(Sort.Direction.ASC, "firstName")); final List<Person> result = TestUtils.toList(cosmosTemplate.find(query, Person.class, containerName)); assertThat(result.size()).isEqualTo(3); assertThat(result.get(0).getFirstName()).isEqualTo("barney"); assertThat(result.get(1).getFirstName()).isEqualTo("fred"); assertThat(result.get(2).getFirstName()).isEqualTo("george"); query.withOffsetAndLimit(1, 1); final List<Person> resultWithLimit = TestUtils.toList(cosmosTemplate.find(query, Person.class, containerName)); assertThat(resultWithLimit.size()).isEqualTo(1); assertThat(resultWithLimit.get(0).getFirstName()).isEqualTo("fred"); } @Test public void testFindAllWithPageableAndSort() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Sort sort = Sort.by(Sort.Direction.DESC, "firstName"); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_3, null, sort); final Page<Person> page = cosmosTemplate.findAll(pageRequest, Person.class, containerName); assertThat(page.getContent().size()).isEqualTo(3); PageTestUtils.validateLastPage(page, PAGE_SIZE_3); final List<Person> result = page.getContent(); assertThat(result.get(0).getFirstName()).isEqualTo(NEW_FIRST_NAME); assertThat(result.get(1).getFirstName()).isEqualTo(NEW_FIRST_NAME); assertThat(result.get(2).getFirstName()).isEqualTo(FIRST_NAME); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindAllWithTwoPagesAndVerifySortOrder() { final Person testPerson4 = new Person("id_4", "barney", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson5 = new Person("id_5", "fred", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); cosmosTemplate.insert(testPerson4, new PartitionKey(personInfo.getPartitionKeyFieldValue(testPerson4))); cosmosTemplate.insert(testPerson5, new PartitionKey(personInfo.getPartitionKeyFieldValue(testPerson5))); final Sort sort = Sort.by(Sort.Direction.ASC, "firstName"); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_3, null, sort); final Page<Person> firstPage = cosmosTemplate.findAll(pageRequest, Person.class, containerName); assertThat(firstPage.getContent().size()).isEqualTo(3); PageTestUtils.validateNonLastPage(firstPage, firstPage.getContent().size()); final List<Person> firstPageResults = firstPage.getContent(); assertThat(firstPageResults.get(0).getFirstName()).isEqualTo(testPerson4.getFirstName()); assertThat(firstPageResults.get(1).getFirstName()).isEqualTo(FIRST_NAME); assertThat(firstPageResults.get(2).getFirstName()).isEqualTo(testPerson5.getFirstName()); final Page<Person> secondPage = cosmosTemplate.findAll(firstPage.nextPageable(), Person.class, containerName); assertThat(secondPage.getContent().size()).isEqualTo(2); PageTestUtils.validateLastPage(secondPage, PAGE_SIZE_3); final List<Person> secondPageResults = secondPage.getContent(); assertThat(secondPageResults.get(0).getFirstName()).isEqualTo(NEW_FIRST_NAME); assertThat(secondPageResults.get(1).getFirstName()).isEqualTo(NEW_FIRST_NAME); } @Test public void testExists() { final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final Boolean exists = cosmosTemplate.exists(query, Person.class, containerName); assertThat(exists).isTrue(); final Criteria criteriaIgnoreCase = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); final CosmosQuery queryIgnoreCase = new CosmosQuery(criteriaIgnoreCase); final Boolean existsIgnoreCase = cosmosTemplate.exists(queryIgnoreCase, Person.class, containerName); assertThat(existsIgnoreCase).isTrue(); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testArrayContainsCriteria() { Criteria hasHobby = Criteria.getInstance(CriteriaType.ARRAY_CONTAINS, "hobbies", Collections.singletonList(HOBBY1), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(hasHobby), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testContainsCriteria() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); Person TEST_PERSON_4 = new Person("id-4", "NEW_FIRST_NAME", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); cosmosTemplate.insert(TEST_PERSON_4, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_4))); Criteria containsCaseSensitive = Criteria.getInstance(CriteriaType.CONTAINING, "firstName", Collections.singletonList("first"), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsCaseSensitive), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON, TEST_PERSON_2, TEST_PERSON_3); Criteria containsNotCaseSensitive = Criteria.getInstance(CriteriaType.CONTAINING, "firstName", Collections.singletonList("first"), Part.IgnoreCaseType.ALWAYS); List<Person> people2 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsNotCaseSensitive), Person.class, containerName)); assertThat(people2).containsExactly(TEST_PERSON, TEST_PERSON_2, TEST_PERSON_3, TEST_PERSON_4); } @Test public void testContainsCriteria2() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); Criteria containsCaseSensitive = Criteria.getInstance(CriteriaType.CONTAINING, "id", Collections.singletonList("1"), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsCaseSensitive), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); Criteria containsCaseSensitive2 = Criteria.getInstance(CriteriaType.CONTAINING, "id", Collections.singletonList("2"), Part.IgnoreCaseType.NEVER); List<Person> people2 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsCaseSensitive2), Person.class, containerName)); assertThat(people2).containsExactly(TEST_PERSON_2); Criteria containsCaseSensitive3 = Criteria.getInstance(CriteriaType.CONTAINING, "id", Collections.singletonList("3"), Part.IgnoreCaseType.NEVER); List<Person> people3 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsCaseSensitive3), Person.class, containerName)); assertThat(people3).containsExactly(TEST_PERSON_3); } @Test public void testNotContainsCriteria() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); Person TEST_PERSON_4 = new Person("id-4", "NEW_FIRST_NAME", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); cosmosTemplate.insert(TEST_PERSON_4, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_4))); Criteria notContainsCaseSensitive = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "firstName", Collections.singletonList("li"), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsCaseSensitive), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON_2, TEST_PERSON_3, TEST_PERSON_4); Criteria notContainsNotCaseSensitive = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "firstName", Collections.singletonList("new"), Part.IgnoreCaseType.ALWAYS); List<Person> people2 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsNotCaseSensitive), Person.class, containerName)); assertThat(people2).containsExactly(TEST_PERSON); } @Test public void testNotContainsCriteria2() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); Criteria notContainsCaseSensitive = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "id", Collections.singletonList("1"), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsCaseSensitive), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON_2, TEST_PERSON_3); Criteria notContainsCaseSensitive2 = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "id", Collections.singletonList("2"), Part.IgnoreCaseType.NEVER); List<Person> people2 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsCaseSensitive2), Person.class, containerName)); assertThat(people2).containsExactly(TEST_PERSON, TEST_PERSON_3); Criteria notContainsCaseSensitive3 = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "id", Collections.singletonList("3"), Part.IgnoreCaseType.NEVER); List<Person> people3 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsCaseSensitive3), Person.class, containerName)); assertThat(people3).containsExactly(TEST_PERSON, TEST_PERSON_2); } @Test public void testIsNotNullCriteriaCaseSensitive() { Criteria hasLastName = Criteria.getInstance(CriteriaType.IS_NOT_NULL, "lastName", Collections.emptyList(), Part.IgnoreCaseType.ALWAYS); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(hasLastName), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testStartsWithCriteriaCaseSensitive() { Criteria nameStartsWith = Criteria.getInstance(CriteriaType.STARTS_WITH, "firstName", Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(nameStartsWith), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testIsEqualCriteriaCaseSensitive() { Criteria nameStartsWith = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(nameStartsWith), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testStringEqualsCriteriaCaseSensitive() { Criteria nameStartsWith = Criteria.getInstance(CriteriaType.STRING_EQUALS, "firstName", Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(nameStartsWith), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testBetweenCriteria() { Criteria ageBetween = Criteria.getInstance(CriteriaType.BETWEEN, "age", Arrays.asList(AGE - 1, AGE + 1), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(ageBetween), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testFindWithEqualCriteriaContainingNestedProperty() { String postalCode = ADDRESSES.get(0).getPostalCode(); String subjectWithNestedProperty = "shippingAddresses[0]['postalCode']"; Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, subjectWithNestedProperty, Collections.singletonList(postalCode), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(criteria), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testRunQueryWithEqualCriteriaContainingSpaces() { String usaPassportId = PASSPORT_IDS_BY_COUNTRY.get("United States of America"); String subjectWithSpaces = "passportIdsByCountry['United States of America']"; Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, subjectWithSpaces, Collections.singletonList(usaPassportId), Part.IgnoreCaseType.NEVER); final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(new CosmosQuery(criteria)); List<Person> people = TestUtils.toList(cosmosTemplate.runQuery(sqlQuerySpec, Person.class, Person.class)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testRunQueryWithSimpleReturnType() { Criteria ageBetween = Criteria.getInstance(CriteriaType.BETWEEN, "age", Arrays.asList(AGE - 1, AGE + 1), Part.IgnoreCaseType.NEVER); final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(new CosmosQuery(ageBetween)); List<Person> people = TestUtils.toList(cosmosTemplate.runQuery(sqlQuerySpec, Person.class, Person.class)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testSliceQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(FIRST_NAME), Part.IgnoreCaseType.NEVER); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_2, null); final CosmosQuery query = new CosmosQuery(criteria).with(pageRequest); final Slice<Person> slice = cosmosTemplate.sliceQuery(query, Person.class, containerName); assertThat(slice.getContent().size()).isEqualTo(1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testRunSliceQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(FIRST_NAME), Part.IgnoreCaseType.NEVER); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_2, null); final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(new CosmosQuery(criteria)); final Slice<Person> slice = cosmosTemplate.runSliceQuery(sqlQuerySpec, pageRequest, Person.class, Person.class); assertThat(slice.getContent().size()).isEqualTo(1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test @Test public void createDatabaseWithThroughput() throws ClassNotFoundException { final String configuredThroughputDbName = TestConstants.DB_NAME + "-configured-throughput"; deleteDatabaseIfExists(configuredThroughputDbName); Integer expectedRequestUnits = 700; final CosmosConfig config = CosmosConfig.builder() .enableDatabaseThroughput(false, expectedRequestUnits) .build(); final CosmosTemplate configuredThroughputCosmosTemplate = createCosmosTemplate(config, configuredThroughputDbName); final CosmosEntityInformation<Person, String> personInfo = new CosmosEntityInformation<>(Person.class); configuredThroughputCosmosTemplate.createContainerIfNotExists(personInfo); final CosmosAsyncDatabase database = client.getDatabase(configuredThroughputDbName); final ThroughputResponse response = database.readThroughput().block(); assertEquals(expectedRequestUnits, response.getProperties().getManualThroughput()); deleteDatabaseIfExists(configuredThroughputDbName); } @Test public void queryWithMaxDegreeOfParallelism() throws ClassNotFoundException { final CosmosConfig config = CosmosConfig.builder() .maxDegreeOfParallelism(20) .build(); final CosmosTemplate maxDegreeOfParallelismCosmosTemplate = createCosmosTemplate(config, TestConstants.DB_NAME); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = maxDegreeOfParallelismCosmosTemplate.count(query, containerName); assertEquals((int) ReflectionTestUtils.getField(maxDegreeOfParallelismCosmosTemplate, "maxDegreeOfParallelism"), 20); } @Test public void queryWithMaxBufferedItemCount() throws ClassNotFoundException { final CosmosConfig config = CosmosConfig.builder() .maxBufferedItemCount(500) .build(); final CosmosTemplate maxBufferedItemCountCosmosTemplate = createCosmosTemplate(config, TestConstants.DB_NAME); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = maxBufferedItemCountCosmosTemplate.count(query, containerName); assertEquals((int) ReflectionTestUtils.getField(maxBufferedItemCountCosmosTemplate, "maxBufferedItemCount"), 500); } @Test public void queryWithResponseContinuationTokenLimitInKb() throws ClassNotFoundException { final CosmosConfig config = CosmosConfig.builder() .responseContinuationTokenLimitInKb(2000) .build(); final CosmosTemplate responseContinuationTokenLimitInKbCosmosTemplate = createCosmosTemplate(config, TestConstants.DB_NAME); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = responseContinuationTokenLimitInKbCosmosTemplate.count(query, containerName); assertEquals((int) ReflectionTestUtils.getField(responseContinuationTokenLimitInKbCosmosTemplate, "responseContinuationTokenLimitInKb"), 2000); } @Test public void queryDatabaseWithQueryMerticsEnabled() throws ClassNotFoundException { final CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(true) .build(); final CosmosTemplate queryMetricsEnabledCosmosTemplate = createCosmosTemplate(config, TestConstants.DB_NAME); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = queryMetricsEnabledCosmosTemplate.count(query, containerName); assertEquals((boolean) ReflectionTestUtils.getField(queryMetricsEnabledCosmosTemplate, "queryMetricsEnabled"), true); } @Test public void userAgentSpringDataCosmosSuffix() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method getUserAgentSuffix = CosmosClientBuilder.class.getDeclaredMethod("getUserAgentSuffix"); getUserAgentSuffix.setAccessible(true); String userAgentSuffix = (String) getUserAgentSuffix.invoke(cosmosClientBuilder); assertThat(userAgentSuffix).contains(Constants.USER_AGENT_SUFFIX); assertThat(userAgentSuffix).contains(PropertyLoader.getProjectVersion()); } private void deleteDatabaseIfExists(String dbName) { CosmosAsyncDatabase database = client.getDatabase(dbName); try { database.delete().block(); } catch (CosmosException ex) { assertEquals(ex.getStatusCode(), 404); } } }
class CosmosTemplateIT { private static final Person TEST_PERSON = new Person(ID_1, FIRST_NAME, LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); private static final Person TEST_PERSON_2 = new Person(ID_2, NEW_FIRST_NAME, NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); private static final Person TEST_PERSON_3 = new Person(ID_3, NEW_FIRST_NAME, NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); private static final BasicItem BASIC_ITEM = new BasicItem(ID_1); private static final String PRECONDITION_IS_NOT_MET = "is not met"; private static final String WRONG_ETAG = "WRONG_ETAG"; private static final String INVALID_ID = "http: private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final JsonNode NEW_PASSPORT_IDS_BY_COUNTRY_JSON = OBJECT_MAPPER.convertValue(NEW_PASSPORT_IDS_BY_COUNTRY, JsonNode.class); private static final CosmosPatchOperations operations = CosmosPatchOperations .create() .replace("/age", PATCH_AGE_1); CosmosPatchOperations multiPatchOperations = CosmosPatchOperations .create() .set("/firstName", PATCH_FIRST_NAME) .replace("/passportIdsByCountry", NEW_PASSPORT_IDS_BY_COUNTRY_JSON) .add("/hobbies/2", PATCH_HOBBY1) .remove("/shippingAddresses/1") .increment("/age", PATCH_AGE_INCREMENT); private static final CosmosPatchItemRequestOptions options = new CosmosPatchItemRequestOptions(); @ClassRule public static final IntegrationTestCollectionManager collectionManager = new IntegrationTestCollectionManager(); private static CosmosAsyncClient client; private static CosmosTemplate cosmosTemplate; private static CosmosEntityInformation<Person, String> personInfo; private static String containerName; private Person insertedPerson; private BasicItem pointReadItem; @Autowired private ApplicationContext applicationContext; @Autowired private CosmosClientBuilder cosmosClientBuilder; @Autowired private CosmosConfig cosmosConfig; @Autowired private ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils; public CosmosTemplateIT() throws JsonProcessingException { } @Before public void setUp() throws ClassNotFoundException { if (cosmosTemplate == null) { client = CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder); personInfo = new CosmosEntityInformation<>(Person.class); containerName = personInfo.getContainerName(); cosmosTemplate = createCosmosTemplate(cosmosConfig, TestConstants.DB_NAME); } collectionManager.ensureContainersCreatedAndEmpty(cosmosTemplate, Person.class, GenIdEntity.class, AuditableEntity.class, BasicItem.class); insertedPerson = cosmosTemplate.insert(Person.class.getSimpleName(), TEST_PERSON, new PartitionKey(TEST_PERSON.getLastName())); pointReadItem = cosmosTemplate.insert(BasicItem.class.getSimpleName(), BASIC_ITEM, new PartitionKey(BASIC_ITEM.getId())); } private CosmosTemplate createCosmosTemplate(CosmosConfig config, String dbName) throws ClassNotFoundException { final CosmosFactory cosmosFactory = new CosmosFactory(client, dbName); final CosmosMappingContext mappingContext = new CosmosMappingContext(); mappingContext.setInitialEntitySet(new EntityScanner(this.applicationContext).scan(Persistent.class)); final MappingCosmosConverter cosmosConverter = new MappingCosmosConverter(mappingContext, null); return new CosmosTemplate(cosmosFactory, config, cosmosConverter); } private void insertPerson(Person person) { cosmosTemplate.insert(person, new PartitionKey(personInfo.getPartitionKeyFieldValue(person))); } @Test public void testInsertDuplicateIdShouldFailWithConflictException() { try { cosmosTemplate.insert(Person.class.getSimpleName(), TEST_PERSON, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); fail(); } catch (CosmosAccessException ex) { assertThat(ex.getCosmosException().getStatusCode()).isEqualTo(TestConstants.CONFLICT_STATUS_CODE); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } } @Test(expected = CosmosAccessException.class) public void testInsertShouldFailIfColumnNotAnnotatedWithAutoGenerate() { final Person person = new Person(null, FIRST_NAME, LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); cosmosTemplate.insert(Person.class.getSimpleName(), person, new PartitionKey(person.getLastName())); } @Test public void testInsertShouldGenerateIdIfColumnAnnotatedWithAutoGenerate() { final GenIdEntity entity = new GenIdEntity(null, "foo"); final GenIdEntity insertedEntity = cosmosTemplate.insert(GenIdEntity.class.getSimpleName(), entity, null); assertThat(insertedEntity.getId()).isNotNull(); } @Test public void testFindAll() { final List<Person> result = TestUtils.toList(cosmosTemplate.findAll(Person.class.getSimpleName(), Person.class)); assertThat(result.size()).isEqualTo(1); assertThat(result.get(0)).isEqualTo(TEST_PERSON); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindByIdPointRead() { final BasicItem result = cosmosTemplate.findById(BasicItem.class.getSimpleName(), BASIC_ITEM.getId(), BasicItem.class); assertEquals(result, BASIC_ITEM); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final BasicItem nullResult = cosmosTemplate.findById(BasicItem.class.getSimpleName(), NOT_EXIST_ID, BasicItem.class); assertThat(nullResult).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics().toString().contains("\"requestOperationType\":\"Read\"")).isTrue(); } @Test public void testFindById() { final Person result = cosmosTemplate.findById(Person.class.getSimpleName(), TEST_PERSON.getId(), Person.class); assertEquals(result, TEST_PERSON); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); final Person nullResult = cosmosTemplate.findById(Person.class.getSimpleName(), NOT_EXIST_ID, Person.class); assertThat(nullResult).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } @Test public void testFindByIdWithInvalidId() { try { cosmosTemplate.findById(BasicItem.class.getSimpleName(), INVALID_ID, BasicItem.class); fail(); } catch (CosmosAccessException ex) { assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } } @Test public void testFindByMultiIds() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); final List<Object> ids = Lists.newArrayList(ID_1, ID_2, ID_3); final List<Person> result = TestUtils.toList(cosmosTemplate.findByIds(ids, Person.class, containerName)); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); final List<Person> expected = Lists.newArrayList(TEST_PERSON, TEST_PERSON_2, TEST_PERSON_3); assertThat(result.size()).isEqualTo(expected.size()); assertThat(result).containsAll(expected); } @Test public void testUpsertNewDocument() { cosmosTemplate.deleteById(Person.class.getSimpleName(), TEST_PERSON.getId(), new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); final String firstName = NEW_FIRST_NAME + "_" + UUID.randomUUID(); final Person newPerson = new Person(TEST_PERSON.getId(), firstName, NEW_FIRST_NAME, null, null, AGE, PASSPORT_IDS_BY_COUNTRY); final Person person = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), newPerson); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); assertEquals(person.getFirstName(), firstName); } @Test public void testUpdateWithReturnEntity() { final Person updated = new Person(TEST_PERSON.getId(), UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses(), AGE, PASSPORT_IDS_BY_COUNTRY); updated.set_etag(insertedPerson.get_etag()); final Person updatedPerson = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), updated); final Person findPersonById = cosmosTemplate.findById(Person.class.getSimpleName(), updatedPerson.getId(), Person.class); assertEquals(updatedPerson, updated); assertThat(updatedPerson.get_etag()).isEqualTo(findPersonById.get_etag()); } @Test public void testUpdate() { final Person updated = new Person(TEST_PERSON.getId(), UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses(), AGE, PASSPORT_IDS_BY_COUNTRY); updated.set_etag(insertedPerson.get_etag()); final Person person = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), updated); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); assertEquals(person, updated); } @Test public void testPatch() { Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, operations); assertEquals(patchedPerson.getAge(), PATCH_AGE_1); } @Test public void testPatchMultiOperations() { Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, multiPatchOperations); assertEquals(patchedPerson.getAge().intValue(), (AGE + PATCH_AGE_INCREMENT)); assertEquals(patchedPerson.getHobbies(), PATCH_HOBBIES); assertEquals(patchedPerson.getFirstName(), PATCH_FIRST_NAME); assertEquals(patchedPerson.getShippingAddresses().size(), 1); assertEquals(patchedPerson.getPassportIdsByCountry(), NEW_PASSPORT_IDS_BY_COUNTRY); } @Test public void testPatchPreConditionSuccess() { options.setFilterPredicate("FROM person p WHERE p.lastName = '"+LAST_NAME+"'"); Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, operations, options); assertEquals(patchedPerson.getAge(), PATCH_AGE_1); } @Test public void testPatchPreConditionFail() { try { options.setFilterPredicate("FROM person p WHERE p.lastName = 'dummy'"); Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, operations, options); assertEquals(patchedPerson.getAge(), PATCH_AGE_1); fail(); } catch (CosmosAccessException ex) { assertThat(ex.getCosmosException().getStatusCode()).isEqualTo(TestConstants.PRECONDITION_FAILED_STATUS_CODE); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } } @Test public void testOptimisticLockWhenUpdatingWithWrongEtag() { final Person updated = new Person(TEST_PERSON.getId(), UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses(), AGE, PASSPORT_IDS_BY_COUNTRY); updated.set_etag(WRONG_ETAG); try { cosmosTemplate.upsert(Person.class.getSimpleName(), updated); } catch (CosmosAccessException e) { assertThat(e.getCosmosException()).isNotNull(); final Throwable cosmosClientException = e.getCosmosException(); assertThat(cosmosClientException).isInstanceOf(CosmosException.class); assertThat(cosmosClientException.getMessage()).contains(PRECONDITION_IS_NOT_MET); assertThat(responseDiagnosticsTestUtils.getDiagnostics()).isNotNull(); final Person unmodifiedPerson = cosmosTemplate.findById(Person.class.getSimpleName(), TEST_PERSON.getId(), Person.class); assertThat(unmodifiedPerson.getFirstName()).isEqualTo(insertedPerson.getFirstName()); return; } fail(); } @Test public void testDeleteById() { cosmosTemplate.insert(TEST_PERSON_2, null); assertThat(cosmosTemplate.count(Person.class.getSimpleName())).isEqualTo(2); cosmosTemplate.deleteById(Person.class.getSimpleName(), TEST_PERSON.getId(), new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final List<Person> result = TestUtils.toList(cosmosTemplate.findAll(Person.class)); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); assertThat(result.size()).isEqualTo(1); assertEquals(result.get(0), TEST_PERSON_2); } @Test public void testDeleteByEntity() { Person insertedPerson = cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(TEST_PERSON_2.getLastName())); assertThat(cosmosTemplate.count(Person.class.getSimpleName())).isEqualTo(2); cosmosTemplate.deleteEntity(Person.class.getSimpleName(), insertedPerson); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final List<Person> result = TestUtils.toList(cosmosTemplate.findAll(Person.class)); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); assertThat(result.size()).isEqualTo(1); assertEquals(result.get(0), TEST_PERSON); } @Test public void testCountByContainer() { final long prevCount = cosmosTemplate.count(containerName); assertThat(prevCount).isEqualTo(1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); final long newCount = cosmosTemplate.count(containerName); assertThat(newCount).isEqualTo(2); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testCountByQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON_2.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = cosmosTemplate.count(query, containerName); assertThat(count).isEqualTo(1); final Criteria criteriaIgnoreCase = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON_2.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); final CosmosQuery queryIgnoreCase = new CosmosQuery(criteriaIgnoreCase); final long countIgnoreCase = cosmosTemplate.count(queryIgnoreCase, containerName); assertThat(countIgnoreCase).isEqualTo(1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindAllPageableMultiPages() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final CosmosPageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_1, null); final Page<Person> page1 = cosmosTemplate.findAll(pageRequest, Person.class, containerName); assertThat(page1.getContent().size()).isEqualTo(PAGE_SIZE_1); PageTestUtils.validateNonLastPage(page1, PAGE_SIZE_1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); final Page<Person> page2 = cosmosTemplate.findAll(page1.nextPageable(), Person.class, containerName); assertThat(page2.getContent().size()).isEqualTo(1); PageTestUtils.validateLastPage(page2, PAGE_SIZE_1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindAllPageableMultiPagesPageSizeTwo() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final CosmosPageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_2, null); final Page<Person> page1 = cosmosTemplate.findAll(pageRequest, Person.class, containerName); final List<Person> resultPage1 = TestUtils.toList(page1); final List<Person> expected = Lists.newArrayList(TEST_PERSON, TEST_PERSON_2); assertThat(resultPage1.size()).isEqualTo(expected.size()); assertThat(resultPage1).containsAll(expected); PageTestUtils.validateNonLastPage(page1, PAGE_SIZE_2); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); final Page<Person> page2 = cosmosTemplate.findAll(page1.nextPageable(), Person.class, containerName); final List<Person> resultPage2 = TestUtils.toList(page2); final List<Person> expected2 = Lists.newArrayList(TEST_PERSON_3); assertThat(resultPage2.size()).isEqualTo(expected2.size()); assertThat(resultPage2).containsAll(expected2); PageTestUtils.validateLastPage(page2, PAGE_SIZE_2); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testPaginationQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(FIRST_NAME), Part.IgnoreCaseType.NEVER); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_2, null); final CosmosQuery query = new CosmosQuery(criteria).with(pageRequest); final Page<Person> page = cosmosTemplate.paginationQuery(query, Person.class, containerName); assertThat(page.getContent().size()).isEqualTo(1); PageTestUtils.validateLastPage(page, PAGE_SIZE_2); final Criteria criteriaIgnoreCase = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(FIRST_NAME.toUpperCase()), Part.IgnoreCaseType.ALWAYS); final CosmosQuery queryIgnoreCase = new CosmosQuery(criteriaIgnoreCase).with(pageRequest); final Page<Person> pageIgnoreCase = cosmosTemplate.paginationQuery(queryIgnoreCase, Person.class, containerName); assertThat(pageIgnoreCase.getContent().size()).isEqualTo(1); PageTestUtils.validateLastPage(pageIgnoreCase, PAGE_SIZE_2); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindWithSortAndLimit() { final Person testPerson4 = new Person("id_4", "fred", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson5 = new Person("id_5", "barney", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson6 = new Person("id_6", "george", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); insertPerson(testPerson4); insertPerson(testPerson5); insertPerson(testPerson6); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "lastName", Collections.singletonList(NEW_LAST_NAME), Part.IgnoreCaseType.ALWAYS); final CosmosQuery query = new CosmosQuery(criteria); query.with(Sort.by(Sort.Direction.ASC, "firstName")); final List<Person> result = TestUtils.toList(cosmosTemplate.find(query, Person.class, containerName)); assertThat(result.size()).isEqualTo(3); assertThat(result.get(0).getFirstName()).isEqualTo("barney"); assertThat(result.get(1).getFirstName()).isEqualTo("fred"); assertThat(result.get(2).getFirstName()).isEqualTo("george"); query.withLimit(1); final List<Person> resultWithLimit = TestUtils.toList(cosmosTemplate.find(query, Person.class, containerName)); assertThat(resultWithLimit.size()).isEqualTo(1); assertThat(resultWithLimit.get(0).getFirstName()).isEqualTo("barney"); } @Test public void testFindWithOffsetAndLimit() { final Person testPerson4 = new Person("id_4", "fred", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson5 = new Person("id_5", "barney", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson6 = new Person("id_6", "george", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); insertPerson(testPerson4); insertPerson(testPerson5); insertPerson(testPerson6); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "lastName", Collections.singletonList(NEW_LAST_NAME), Part.IgnoreCaseType.ALWAYS); final CosmosQuery query = new CosmosQuery(criteria); query.with(Sort.by(Sort.Direction.ASC, "firstName")); final List<Person> result = TestUtils.toList(cosmosTemplate.find(query, Person.class, containerName)); assertThat(result.size()).isEqualTo(3); assertThat(result.get(0).getFirstName()).isEqualTo("barney"); assertThat(result.get(1).getFirstName()).isEqualTo("fred"); assertThat(result.get(2).getFirstName()).isEqualTo("george"); query.withOffsetAndLimit(1, 1); final List<Person> resultWithLimit = TestUtils.toList(cosmosTemplate.find(query, Person.class, containerName)); assertThat(resultWithLimit.size()).isEqualTo(1); assertThat(resultWithLimit.get(0).getFirstName()).isEqualTo("fred"); } @Test public void testFindAllWithPageableAndSort() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Sort sort = Sort.by(Sort.Direction.DESC, "firstName"); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_3, null, sort); final Page<Person> page = cosmosTemplate.findAll(pageRequest, Person.class, containerName); assertThat(page.getContent().size()).isEqualTo(3); PageTestUtils.validateLastPage(page, PAGE_SIZE_3); final List<Person> result = page.getContent(); assertThat(result.get(0).getFirstName()).isEqualTo(NEW_FIRST_NAME); assertThat(result.get(1).getFirstName()).isEqualTo(NEW_FIRST_NAME); assertThat(result.get(2).getFirstName()).isEqualTo(FIRST_NAME); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindAllWithTwoPagesAndVerifySortOrder() { final Person testPerson4 = new Person("id_4", "barney", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); final Person testPerson5 = new Person("id_5", "fred", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); cosmosTemplate.insert(testPerson4, new PartitionKey(personInfo.getPartitionKeyFieldValue(testPerson4))); cosmosTemplate.insert(testPerson5, new PartitionKey(personInfo.getPartitionKeyFieldValue(testPerson5))); final Sort sort = Sort.by(Sort.Direction.ASC, "firstName"); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_3, null, sort); final Page<Person> firstPage = cosmosTemplate.findAll(pageRequest, Person.class, containerName); assertThat(firstPage.getContent().size()).isEqualTo(3); PageTestUtils.validateNonLastPage(firstPage, firstPage.getContent().size()); final List<Person> firstPageResults = firstPage.getContent(); assertThat(firstPageResults.get(0).getFirstName()).isEqualTo(testPerson4.getFirstName()); assertThat(firstPageResults.get(1).getFirstName()).isEqualTo(FIRST_NAME); assertThat(firstPageResults.get(2).getFirstName()).isEqualTo(testPerson5.getFirstName()); final Page<Person> secondPage = cosmosTemplate.findAll(firstPage.nextPageable(), Person.class, containerName); assertThat(secondPage.getContent().size()).isEqualTo(2); PageTestUtils.validateLastPage(secondPage, PAGE_SIZE_3); final List<Person> secondPageResults = secondPage.getContent(); assertThat(secondPageResults.get(0).getFirstName()).isEqualTo(NEW_FIRST_NAME); assertThat(secondPageResults.get(1).getFirstName()).isEqualTo(NEW_FIRST_NAME); } @Test public void testExists() { final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final Boolean exists = cosmosTemplate.exists(query, Person.class, containerName); assertThat(exists).isTrue(); final Criteria criteriaIgnoreCase = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); final CosmosQuery queryIgnoreCase = new CosmosQuery(criteriaIgnoreCase); final Boolean existsIgnoreCase = cosmosTemplate.exists(queryIgnoreCase, Person.class, containerName); assertThat(existsIgnoreCase).isTrue(); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testArrayContainsCriteria() { Criteria hasHobby = Criteria.getInstance(CriteriaType.ARRAY_CONTAINS, "hobbies", Collections.singletonList(HOBBY1), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(hasHobby), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testContainsCriteria() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); Person TEST_PERSON_4 = new Person("id-4", "NEW_FIRST_NAME", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); cosmosTemplate.insert(TEST_PERSON_4, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_4))); Criteria containsCaseSensitive = Criteria.getInstance(CriteriaType.CONTAINING, "firstName", Collections.singletonList("first"), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsCaseSensitive), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON, TEST_PERSON_2, TEST_PERSON_3); Criteria containsNotCaseSensitive = Criteria.getInstance(CriteriaType.CONTAINING, "firstName", Collections.singletonList("first"), Part.IgnoreCaseType.ALWAYS); List<Person> people2 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsNotCaseSensitive), Person.class, containerName)); assertThat(people2).containsExactly(TEST_PERSON, TEST_PERSON_2, TEST_PERSON_3, TEST_PERSON_4); } @Test public void testContainsCriteria2() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); Criteria containsCaseSensitive = Criteria.getInstance(CriteriaType.CONTAINING, "id", Collections.singletonList("1"), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsCaseSensitive), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); Criteria containsCaseSensitive2 = Criteria.getInstance(CriteriaType.CONTAINING, "id", Collections.singletonList("2"), Part.IgnoreCaseType.NEVER); List<Person> people2 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsCaseSensitive2), Person.class, containerName)); assertThat(people2).containsExactly(TEST_PERSON_2); Criteria containsCaseSensitive3 = Criteria.getInstance(CriteriaType.CONTAINING, "id", Collections.singletonList("3"), Part.IgnoreCaseType.NEVER); List<Person> people3 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(containsCaseSensitive3), Person.class, containerName)); assertThat(people3).containsExactly(TEST_PERSON_3); } @Test public void testNotContainsCriteria() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); Person TEST_PERSON_4 = new Person("id-4", "NEW_FIRST_NAME", NEW_LAST_NAME, HOBBIES, ADDRESSES, AGE, PASSPORT_IDS_BY_COUNTRY); cosmosTemplate.insert(TEST_PERSON_4, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_4))); Criteria notContainsCaseSensitive = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "firstName", Collections.singletonList("li"), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsCaseSensitive), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON_2, TEST_PERSON_3, TEST_PERSON_4); Criteria notContainsNotCaseSensitive = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "firstName", Collections.singletonList("new"), Part.IgnoreCaseType.ALWAYS); List<Person> people2 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsNotCaseSensitive), Person.class, containerName)); assertThat(people2).containsExactly(TEST_PERSON); } @Test public void testNotContainsCriteria2() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); Criteria notContainsCaseSensitive = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "id", Collections.singletonList("1"), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsCaseSensitive), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON_2, TEST_PERSON_3); Criteria notContainsCaseSensitive2 = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "id", Collections.singletonList("2"), Part.IgnoreCaseType.NEVER); List<Person> people2 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsCaseSensitive2), Person.class, containerName)); assertThat(people2).containsExactly(TEST_PERSON, TEST_PERSON_3); Criteria notContainsCaseSensitive3 = Criteria.getInstance(CriteriaType.NOT_CONTAINING, "id", Collections.singletonList("3"), Part.IgnoreCaseType.NEVER); List<Person> people3 = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(notContainsCaseSensitive3), Person.class, containerName)); assertThat(people3).containsExactly(TEST_PERSON, TEST_PERSON_2); } @Test public void testIsNotNullCriteriaCaseSensitive() { Criteria hasLastName = Criteria.getInstance(CriteriaType.IS_NOT_NULL, "lastName", Collections.emptyList(), Part.IgnoreCaseType.ALWAYS); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(hasLastName), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testStartsWithCriteriaCaseSensitive() { Criteria nameStartsWith = Criteria.getInstance(CriteriaType.STARTS_WITH, "firstName", Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(nameStartsWith), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testIsEqualCriteriaCaseSensitive() { Criteria nameStartsWith = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(nameStartsWith), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testStringEqualsCriteriaCaseSensitive() { Criteria nameStartsWith = Criteria.getInstance(CriteriaType.STRING_EQUALS, "firstName", Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(nameStartsWith), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testBetweenCriteria() { Criteria ageBetween = Criteria.getInstance(CriteriaType.BETWEEN, "age", Arrays.asList(AGE - 1, AGE + 1), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(ageBetween), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testFindWithEqualCriteriaContainingNestedProperty() { String postalCode = ADDRESSES.get(0).getPostalCode(); String subjectWithNestedProperty = "shippingAddresses[0]['postalCode']"; Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, subjectWithNestedProperty, Collections.singletonList(postalCode), Part.IgnoreCaseType.NEVER); List<Person> people = TestUtils.toList(cosmosTemplate.find(new CosmosQuery(criteria), Person.class, containerName)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testRunQueryWithEqualCriteriaContainingSpaces() { String usaPassportId = PASSPORT_IDS_BY_COUNTRY.get("United States of America"); String subjectWithSpaces = "passportIdsByCountry['United States of America']"; Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, subjectWithSpaces, Collections.singletonList(usaPassportId), Part.IgnoreCaseType.NEVER); final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(new CosmosQuery(criteria)); List<Person> people = TestUtils.toList(cosmosTemplate.runQuery(sqlQuerySpec, Person.class, Person.class)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testRunQueryWithSimpleReturnType() { Criteria ageBetween = Criteria.getInstance(CriteriaType.BETWEEN, "age", Arrays.asList(AGE - 1, AGE + 1), Part.IgnoreCaseType.NEVER); final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(new CosmosQuery(ageBetween)); List<Person> people = TestUtils.toList(cosmosTemplate.runQuery(sqlQuerySpec, Person.class, Person.class)); assertThat(people).containsExactly(TEST_PERSON); } @Test public void testSliceQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(FIRST_NAME), Part.IgnoreCaseType.NEVER); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_2, null); final CosmosQuery query = new CosmosQuery(criteria).with(pageRequest); final Slice<Person> slice = cosmosTemplate.sliceQuery(query, Person.class, containerName); assertThat(slice.getContent().size()).isEqualTo(1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testRunSliceQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(FIRST_NAME), Part.IgnoreCaseType.NEVER); final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_2, null); final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(new CosmosQuery(criteria)); final Slice<Person> slice = cosmosTemplate.runSliceQuery(sqlQuerySpec, pageRequest, Person.class, Person.class); assertThat(slice.getContent().size()).isEqualTo(1); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test @Test public void createDatabaseWithThroughput() throws ClassNotFoundException { final String configuredThroughputDbName = TestConstants.DB_NAME + "-configured-throughput"; deleteDatabaseIfExists(configuredThroughputDbName); Integer expectedRequestUnits = 700; final CosmosConfig config = CosmosConfig.builder() .enableDatabaseThroughput(false, expectedRequestUnits) .build(); final CosmosTemplate configuredThroughputCosmosTemplate = createCosmosTemplate(config, configuredThroughputDbName); final CosmosEntityInformation<Person, String> personInfo = new CosmosEntityInformation<>(Person.class); configuredThroughputCosmosTemplate.createContainerIfNotExists(personInfo); final CosmosAsyncDatabase database = client.getDatabase(configuredThroughputDbName); final ThroughputResponse response = database.readThroughput().block(); assertEquals(expectedRequestUnits, response.getProperties().getManualThroughput()); deleteDatabaseIfExists(configuredThroughputDbName); } @Test public void queryWithMaxDegreeOfParallelism() throws ClassNotFoundException { final CosmosConfig config = CosmosConfig.builder() .maxDegreeOfParallelism(20) .build(); final CosmosTemplate maxDegreeOfParallelismCosmosTemplate = createCosmosTemplate(config, TestConstants.DB_NAME); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = maxDegreeOfParallelismCosmosTemplate.count(query, containerName); assertEquals((int) ReflectionTestUtils.getField(maxDegreeOfParallelismCosmosTemplate, "maxDegreeOfParallelism"), 20); } @Test public void queryWithMaxBufferedItemCount() throws ClassNotFoundException { final CosmosConfig config = CosmosConfig.builder() .maxBufferedItemCount(500) .build(); final CosmosTemplate maxBufferedItemCountCosmosTemplate = createCosmosTemplate(config, TestConstants.DB_NAME); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = maxBufferedItemCountCosmosTemplate.count(query, containerName); assertEquals((int) ReflectionTestUtils.getField(maxBufferedItemCountCosmosTemplate, "maxBufferedItemCount"), 500); } @Test public void queryWithResponseContinuationTokenLimitInKb() throws ClassNotFoundException { final CosmosConfig config = CosmosConfig.builder() .responseContinuationTokenLimitInKb(2000) .build(); final CosmosTemplate responseContinuationTokenLimitInKbCosmosTemplate = createCosmosTemplate(config, TestConstants.DB_NAME); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = responseContinuationTokenLimitInKbCosmosTemplate.count(query, containerName); assertEquals((int) ReflectionTestUtils.getField(responseContinuationTokenLimitInKbCosmosTemplate, "responseContinuationTokenLimitInKb"), 2000); } @Test public void queryDatabaseWithQueryMerticsEnabled() throws ClassNotFoundException { final CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(true) .build(); final CosmosTemplate queryMetricsEnabledCosmosTemplate = createCosmosTemplate(config, TestConstants.DB_NAME); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final CosmosQuery query = new CosmosQuery(criteria); final long count = queryMetricsEnabledCosmosTemplate.count(query, containerName); assertEquals((boolean) ReflectionTestUtils.getField(queryMetricsEnabledCosmosTemplate, "queryMetricsEnabled"), true); } @Test public void userAgentSpringDataCosmosSuffix() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method getUserAgentSuffix = CosmosClientBuilder.class.getDeclaredMethod("getUserAgentSuffix"); getUserAgentSuffix.setAccessible(true); String userAgentSuffix = (String) getUserAgentSuffix.invoke(cosmosClientBuilder); assertThat(userAgentSuffix).contains(Constants.USER_AGENT_SUFFIX); assertThat(userAgentSuffix).contains(PropertyLoader.getProjectVersion()); } private void deleteDatabaseIfExists(String dbName) { CosmosAsyncDatabase database = client.getDatabase(dbName); try { database.delete().block(); } catch (CosmosException ex) { assertEquals(ex.getStatusCode(), 404); } } }
Same as HashMap, don't do this. Either use `Arrays.asList` or use a `List xxx = new ArrayList(); xxx.add(..);`.
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = new ArrayList<>(); lstSubProtectionPolicy.add(new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays( new ArrayList<DayOfWeek>() { { add(DayOfWeek.SUNDAY); add(DayOfWeek.TUESDAY); } }) .withScheduleRunTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } })) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek( new ArrayList<DayOfWeek>() { { add(DayOfWeek.SUNDAY); add(DayOfWeek.TUESDAY); } }) .withRetentionTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } }) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek( new ArrayList<DayOfWeek>() { { add(DayOfWeek.SUNDAY); } }) .withWeeksOfTheMonth( new ArrayList<WeekOfMonth>() { { add(WeekOfMonth.SECOND); } })) .withRetentionTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } }) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear( new ArrayList<MonthOfYear>() { { add(MonthOfYear.JANUARY); add(MonthOfYear.JUNE); add(MonthOfYear.DECEMBER); } }) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek( new ArrayList<DayOfWeek>() { { add(DayOfWeek.SUNDAY); } }) .withWeeksOfTheMonth( new ArrayList<WeekOfMonth>() { { add(WeekOfMonth.LAST); } })) .withRetentionTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } }) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS))))); lstSubProtectionPolicy.add(new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays( new ArrayList<DayOfWeek>() { { add(DayOfWeek.FRIDAY); } }) .withScheduleRunTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } })) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS)))); lstSubProtectionPolicy.add(new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
})
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Fixed in the new version.
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = new ArrayList<>(); lstSubProtectionPolicy.add(new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays( new ArrayList<DayOfWeek>() { { add(DayOfWeek.SUNDAY); add(DayOfWeek.TUESDAY); } }) .withScheduleRunTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } })) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek( new ArrayList<DayOfWeek>() { { add(DayOfWeek.SUNDAY); add(DayOfWeek.TUESDAY); } }) .withRetentionTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } }) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek( new ArrayList<DayOfWeek>() { { add(DayOfWeek.SUNDAY); } }) .withWeeksOfTheMonth( new ArrayList<WeekOfMonth>() { { add(WeekOfMonth.SECOND); } })) .withRetentionTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } }) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear( new ArrayList<MonthOfYear>() { { add(MonthOfYear.JANUARY); add(MonthOfYear.JUNE); add(MonthOfYear.DECEMBER); } }) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek( new ArrayList<DayOfWeek>() { { add(DayOfWeek.SUNDAY); } }) .withWeeksOfTheMonth( new ArrayList<WeekOfMonth>() { { add(WeekOfMonth.LAST); } })) .withRetentionTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } }) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS))))); lstSubProtectionPolicy.add(new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays( new ArrayList<DayOfWeek>() { { add(DayOfWeek.FRIDAY); } }) .withScheduleRunTimes( new ArrayList<OffsetDateTime>() { { add(OffsetDateTime.parse("2018-01-24T10:00:00Z")); } })) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS)))); lstSubProtectionPolicy.add(new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
})
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Curiosity only. Why don't service complain when schedule time is 3 years before?
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
These codes are excerpted from `ProtectionPoliciesCreateOrUpdateSamples# createOrUpdateFullAzureWorkloadProtectionPolicy`, which may not be verified it in the backend. Now the schedule time has been fixed in the new version.
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Would it work for e.g. `OffsetDateTime.now().plusDays(1)` (one day in future)?
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Tried this way of setting, but the following exception occurred: ![image](https://github.com/Azure/azure-sdk-for-java/assets/74638143/b977cd43-23fb-46f1-a941-410f08429236)
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
OK. If this does not work, I am fine with current code. Though personally my guess is that there is certain aspect in the datetime rfc3339 that service not able to parse, either the microsecond, or the timezone. Wondering whether this would work `OffsetDateTime.now().withNano(0).withOffsetSameInstant(ZoneOffset.UTC)` (i.e. remove the microsecond and timezone to UTC).
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Maybe use `OffsetDateTime.now().plus(1, ChronoUnit.DAYS)` to avoid scheduling in past time? Same for other OffsetDateTimes.
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
I've tried this and found that only the following date formats work with `yyyy-mm-ddThh:mm:ssZ`。
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
I've tried this and found that only the following date formats work with `yyyy-mm-ddThh:mm:ssZ`
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Got it. You could try ```java OffsetDateTime.parse(OffsetDateTime.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ss'Z'"))) ``` Though it's a bit overkill..
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2023-06-13T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
I assume `OffsetDateTime.now().withNano(0).withOffsetSameInstant(ZoneOffset.UTC)` would give you `yyyy-mm-ddThh:mm:ssZ`?
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
I found the rule of `DateTime`, now fixed in the new version.
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z")))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
.withScheduleRunTimes(Arrays.asList(OffsetDateTime.parse("2018-01-24T10:00:00Z"))))
public void testCreateProtectionPolicy() { Vault vault = null; ProtectionPolicyResource protectionPolicyResource = null; String randomPadding = randomPadding(); try { String vaultName = "vault" + randomPadding; String policyName = "policy" + randomPadding; OffsetDateTime scheduleDateTime = OffsetDateTime.parse( OffsetDateTime.now(Clock.systemUTC()) .withNano(0).withMinute(0).withSecond(0) .plusDays(1).format(DateTimeFormatter.ISO_INSTANT)); List<SubProtectionPolicy> lstSubProtectionPolicy = Arrays.asList( new SubProtectionPolicy() .withPolicyType(PolicyType.FULL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new LongTermRetentionPolicy() .withWeeklySchedule( new WeeklyRetentionSchedule() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY, DayOfWeek.TUESDAY)) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(2) .withDurationType(RetentionDurationType.WEEKS))) .withMonthlySchedule( new MonthlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.SECOND))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.MONTHS))) .withYearlySchedule( new YearlyRetentionSchedule() .withRetentionScheduleFormatType(RetentionScheduleFormat.WEEKLY) .withMonthsOfYear(Arrays.asList(MonthOfYear.JANUARY, MonthOfYear.JUNE, MonthOfYear.DECEMBER)) .withRetentionScheduleWeekly( new WeeklyRetentionFormat() .withDaysOfTheWeek(Arrays.asList(DayOfWeek.SUNDAY)) .withWeeksOfTheMonth(Arrays.asList(WeekOfMonth.LAST))) .withRetentionTimes(Arrays.asList(scheduleDateTime)) .withRetentionDuration( new RetentionDuration() .withCount(1) .withDurationType(RetentionDurationType.YEARS)))), new SubProtectionPolicy() .withPolicyType(PolicyType.DIFFERENTIAL) .withSchedulePolicy( new SimpleSchedulePolicy() .withScheduleRunFrequency(ScheduleRunType.WEEKLY) .withScheduleRunDays(Arrays.asList(DayOfWeek.FRIDAY)) .withScheduleRunTimes(Arrays.asList(scheduleDateTime))) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(8) .withDurationType(RetentionDurationType.DAYS))), new SubProtectionPolicy() .withPolicyType(PolicyType.LOG) .withSchedulePolicy(new LogSchedulePolicy().withScheduleFrequencyInMins(60)) .withRetentionPolicy( new SimpleRetentionPolicy() .withRetentionDuration( new RetentionDuration() .withCount(7) .withDurationType(RetentionDurationType.DAYS)))); vault = recoveryServicesManager.vaults() .define(vaultName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new Sku().withName(SkuName.RS0).withTier("Standard")) .withProperties(new VaultProperties() .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) .withRestoreSettings(new RestoreSettings() .withCrossSubscriptionRestoreSettings( new CrossSubscriptionRestoreSettings() .withCrossSubscriptionRestoreState(CrossSubscriptionRestoreState.ENABLED)))) .create(); protectionPolicyResource = recoveryServicesBackupManager.protectionPolicies() .define(policyName) .withRegion(REGION) .withExistingVault(vaultName, resourceGroupName) .withProperties( new AzureVmWorkloadProtectionPolicy() .withWorkLoadType(WorkloadType.SQLDATA_BASE) .withSettings(new Settings().withTimeZone("Pacific Standard Time").withIssqlcompression(false)) .withSubProtectionPolicy(lstSubProtectionPolicy) ) .create(); protectionPolicyResource.refresh(); Assertions.assertEquals(protectionPolicyResource.name(), policyName); Assertions.assertEquals(protectionPolicyResource.name(), recoveryServicesBackupManager.protectionPolicies().getById(protectionPolicyResource.id()).name()); } finally { if (protectionPolicyResource != null) { recoveryServicesBackupManager.protectionPolicies().deleteById(protectionPolicyResource.id()); } if (vault != null) { recoveryServicesManager.vaults().deleteById(vault.id()); } } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class RecoveryServicesBackupManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private RecoveryServicesBackupManager recoveryServicesBackupManager; private RecoveryServicesManager recoveryServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); recoveryServicesManager = RecoveryServicesManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); recoveryServicesBackupManager = RecoveryServicesBackupManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
nit, `distinct()` seems unnecessary IMHO, though it doesn't hurt to have it. Currently we don't have `equals()` defined in `LogSettings`, so it has no effect anyways.. And both are in `HashSet`, and they have different non-null property(`category` vs `categoryGroup`), so there shouldn't be any duplication in the first place.
public Mono<DiagnosticSetting> createResourceAsync() { this.innerModel() .withLogs(new ArrayList<>( Stream.concat(logSet.values().stream(), logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList()))); this.innerModel().withMetrics(new ArrayList<>(metricSet.values())); return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .createOrUpdateAsync(this.resourceId, this.name(), this.innerModel()) .map(innerToFluentMap(this)); }
logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList())));
public Mono<DiagnosticSetting> createResourceAsync() { this.innerModel() .withLogs(new ArrayList<>( Stream.concat(logSet.values().stream(), logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList()))); this.innerModel().withMetrics(new ArrayList<>(metricSet.values())); return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .createOrUpdateAsync(this.resourceId, this.name(), this.innerModel()) .map(innerToFluentMap(this)); }
class DiagnosticSettingImpl extends CreatableUpdatableImpl<DiagnosticSetting, DiagnosticSettingsResourceInner, DiagnosticSettingImpl> implements DiagnosticSetting, DiagnosticSetting.Definition, DiagnosticSetting.Update { private final ClientLogger logger = new ClientLogger(getClass()); public static final String DIAGNOSTIC_SETTINGS_URI = "/providers/microsoft.insights/diagnosticSettings/"; private String resourceId; private TreeMap<String, MetricSettings> metricSet; private TreeMap<String, LogSettings> logSet; private TreeMap<String, LogSettings> logCategoryGroupSet; private final MonitorManager myManager; DiagnosticSettingImpl( String name, DiagnosticSettingsResourceInner innerModel, final MonitorManager monitorManager) { super(name, innerModel); this.myManager = monitorManager; initializeSets(); } @Override public DiagnosticSettingImpl withResource(String resourceId) { this.resourceId = resourceId; return this; } @Override public DiagnosticSettingImpl withStorageAccount(String storageAccountId) { this.innerModel().withStorageAccountId(storageAccountId); return this; } @Override public DiagnosticSettingImpl withLogAnalytics(String workspaceId) { this.innerModel().withWorkspaceId(workspaceId); return this; } @Override public DiagnosticSettingImpl withoutLogAnalytics() { this.innerModel().withWorkspaceId(null); return this; } @Override public DiagnosticSettingImpl withoutStorageAccount() { this.innerModel().withStorageAccountId(null); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId) { this.innerModel().withEventHubAuthorizationRuleId(eventHubAuthorizationRuleId); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId, String eventHubName) { this.withEventHub(eventHubAuthorizationRuleId); this.innerModel().withEventHubName(eventHubName); return this; } @Override public DiagnosticSettingImpl withoutEventHub() { this.innerModel().withEventHubAuthorizationRuleId(null); this.innerModel().withEventHubName(null); return this; } @Override public DiagnosticSettingImpl withMetric(String category, Duration timeGrain, int retentionDays) { MetricSettings nm = new MetricSettings(); nm.withCategory(category); nm.withEnabled(true); nm.withRetentionPolicy(new RetentionPolicy()); nm.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nm.retentionPolicy().withEnabled(true); } nm.withTimeGrain(timeGrain); this.metricSet.put(category, nm); return this; } @Override public DiagnosticSettingImpl withLog(String category, int retentionDays) { LogSettings nl = new LogSettings(); nl.withCategory(category); nl.withEnabled(true); nl.withRetentionPolicy(new RetentionPolicy()); nl.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nl.retentionPolicy().withEnabled(true); } this.logSet.put(category, nl); return this; } @Override public DiagnosticSettingImpl withLogsAndMetrics( List<DiagnosticSettingsCategory> categories, Duration timeGrain, int retentionDays) { for (DiagnosticSettingsCategory dsc : categories) { if (dsc.type() == CategoryType.METRICS) { this.withMetric(dsc.name(), timeGrain, retentionDays); } else if (dsc.type() == CategoryType.LOGS) { this.withLog(dsc.name(), retentionDays); } else { throw logger.logExceptionAsError( new UnsupportedOperationException(dsc.type().toString() + " is unsupported.")); } } return this; } @Override public DiagnosticSettingImpl withoutMetric(String category) { this.metricSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLog(String category) { this.logSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLogs() { this.logSet.clear(); return this; } @Override public DiagnosticSettingImpl withoutMetrics() { this.metricSet.clear(); return this; } @Override public String id() { return this.innerModel().id(); } @Override public String resourceId() { return this.resourceId; } @Override public String storageAccountId() { return this.innerModel().storageAccountId(); } @Override public String eventHubAuthorizationRuleId() { return this.innerModel().eventHubAuthorizationRuleId(); } @Override public String eventHubName() { return this.innerModel().eventHubName(); } @Override public List<MetricSettings> metrics() { if (this.innerModel().metrics() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().metrics()); } @Override public List<LogSettings> logs() { if (this.innerModel().logs() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().logs()); } @Override public String workspaceId() { return this.innerModel().workspaceId(); } @Override public MonitorManager manager() { return this.myManager; } @Override public boolean isInCreateMode() { return this.innerModel().id() == null; } @Override @Override protected Mono<DiagnosticSettingsResourceInner> getInnerAsync() { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(this.resourceId, this.name()); } @Override public void setInner(DiagnosticSettingsResourceInner inner) { super.setInner(inner); initializeSets(); this.metricSet.clear(); this.logSet.clear(); if (!isInCreateMode()) { this.resourceId = inner .id() .substring( 0, this.innerModel().id().length() - (DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI + this.innerModel().name()).length()); for (MetricSettings ms : this.metrics()) { if (ms.category() != null) { this.metricSet.put(ms.category(), ms); } } for (LogSettings ls : this.logs()) { if (ls.category() != null) { this.logSet.put(ls.category(), ls); } else if (ls.categoryGroup() != null) { this.logCategoryGroupSet.put(ls.categoryGroup(), ls); } } } } private void initializeSets() { if (this.metricSet == null) { this.metricSet = new TreeMap<>(); } if (this.logSet == null) { this.logSet = new TreeMap<>(); } if (this.logCategoryGroupSet == null) { this.logCategoryGroupSet = new TreeMap<>(); } } }
class DiagnosticSettingImpl extends CreatableUpdatableImpl<DiagnosticSetting, DiagnosticSettingsResourceInner, DiagnosticSettingImpl> implements DiagnosticSetting, DiagnosticSetting.Definition, DiagnosticSetting.Update { private final ClientLogger logger = new ClientLogger(getClass()); public static final String DIAGNOSTIC_SETTINGS_URI = "/providers/microsoft.insights/diagnosticSettings/"; private String resourceId; private TreeMap<String, MetricSettings> metricSet; private TreeMap<String, LogSettings> logSet; private TreeMap<String, LogSettings> logCategoryGroupSet; private final MonitorManager myManager; DiagnosticSettingImpl( String name, DiagnosticSettingsResourceInner innerModel, final MonitorManager monitorManager) { super(name, innerModel); this.myManager = monitorManager; initializeSets(); } @Override public DiagnosticSettingImpl withResource(String resourceId) { this.resourceId = resourceId; return this; } @Override public DiagnosticSettingImpl withStorageAccount(String storageAccountId) { this.innerModel().withStorageAccountId(storageAccountId); return this; } @Override public DiagnosticSettingImpl withLogAnalytics(String workspaceId) { this.innerModel().withWorkspaceId(workspaceId); return this; } @Override public DiagnosticSettingImpl withoutLogAnalytics() { this.innerModel().withWorkspaceId(null); return this; } @Override public DiagnosticSettingImpl withoutStorageAccount() { this.innerModel().withStorageAccountId(null); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId) { this.innerModel().withEventHubAuthorizationRuleId(eventHubAuthorizationRuleId); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId, String eventHubName) { this.withEventHub(eventHubAuthorizationRuleId); this.innerModel().withEventHubName(eventHubName); return this; } @Override public DiagnosticSettingImpl withoutEventHub() { this.innerModel().withEventHubAuthorizationRuleId(null); this.innerModel().withEventHubName(null); return this; } @Override public DiagnosticSettingImpl withMetric(String category, Duration timeGrain, int retentionDays) { MetricSettings nm = new MetricSettings(); nm.withCategory(category); nm.withEnabled(true); nm.withRetentionPolicy(new RetentionPolicy()); nm.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nm.retentionPolicy().withEnabled(true); } nm.withTimeGrain(timeGrain); this.metricSet.put(category, nm); return this; } @Override public DiagnosticSettingImpl withLog(String category, int retentionDays) { LogSettings nl = new LogSettings(); nl.withCategory(category); nl.withEnabled(true); nl.withRetentionPolicy(new RetentionPolicy()); nl.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nl.retentionPolicy().withEnabled(true); } this.logSet.put(category, nl); return this; } @Override public DiagnosticSettingImpl withLogsAndMetrics( List<DiagnosticSettingsCategory> categories, Duration timeGrain, int retentionDays) { for (DiagnosticSettingsCategory dsc : categories) { if (dsc.type() == CategoryType.METRICS) { this.withMetric(dsc.name(), timeGrain, retentionDays); } else if (dsc.type() == CategoryType.LOGS) { this.withLog(dsc.name(), retentionDays); } else { throw logger.logExceptionAsError( new UnsupportedOperationException(dsc.type().toString() + " is unsupported.")); } } return this; } @Override public DiagnosticSettingImpl withoutMetric(String category) { this.metricSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLog(String category) { this.logSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLogs() { this.logSet.clear(); return this; } @Override public DiagnosticSettingImpl withoutMetrics() { this.metricSet.clear(); return this; } @Override public String id() { return this.innerModel().id(); } @Override public String resourceId() { return this.resourceId; } @Override public String storageAccountId() { return this.innerModel().storageAccountId(); } @Override public String eventHubAuthorizationRuleId() { return this.innerModel().eventHubAuthorizationRuleId(); } @Override public String eventHubName() { return this.innerModel().eventHubName(); } @Override public List<MetricSettings> metrics() { if (this.innerModel().metrics() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().metrics()); } @Override public List<LogSettings> logs() { if (this.innerModel().logs() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().logs()); } @Override public String workspaceId() { return this.innerModel().workspaceId(); } @Override public MonitorManager manager() { return this.myManager; } @Override public boolean isInCreateMode() { return this.innerModel().id() == null; } @Override @Override protected Mono<DiagnosticSettingsResourceInner> getInnerAsync() { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(this.resourceId, this.name()); } @Override public void setInner(DiagnosticSettingsResourceInner inner) { super.setInner(inner); initializeSets(); this.metricSet.clear(); this.logSet.clear(); if (!isInCreateMode()) { this.resourceId = inner .id() .substring( 0, this.innerModel().id().length() - (DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI + this.innerModel().name()).length()); for (MetricSettings ms : this.metrics()) { if (ms.category() != null) { this.metricSet.put(ms.category(), ms); } } for (LogSettings ls : this.logs()) { if (ls.category() != null) { this.logSet.put(ls.category(), ls); } else if (ls.categoryGroup() != null) { this.logCategoryGroupSet.put(ls.categoryGroup(), ls); } } } } private void initializeSets() { if (this.metricSet == null) { this.metricSet = new TreeMap<>(); } if (this.logSet == null) { this.logSet = new TreeMap<>(); } if (this.logCategoryGroupSet == null) { this.logCategoryGroupSet = new TreeMap<>(); } } }
I was thinking in case a metric name and log name overlapped (not likely I suppose). Happy to remove. I'm away from my computer now but I can update later today.
public Mono<DiagnosticSetting> createResourceAsync() { this.innerModel() .withLogs(new ArrayList<>( Stream.concat(logSet.values().stream(), logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList()))); this.innerModel().withMetrics(new ArrayList<>(metricSet.values())); return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .createOrUpdateAsync(this.resourceId, this.name(), this.innerModel()) .map(innerToFluentMap(this)); }
logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList())));
public Mono<DiagnosticSetting> createResourceAsync() { this.innerModel() .withLogs(new ArrayList<>( Stream.concat(logSet.values().stream(), logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList()))); this.innerModel().withMetrics(new ArrayList<>(metricSet.values())); return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .createOrUpdateAsync(this.resourceId, this.name(), this.innerModel()) .map(innerToFluentMap(this)); }
class DiagnosticSettingImpl extends CreatableUpdatableImpl<DiagnosticSetting, DiagnosticSettingsResourceInner, DiagnosticSettingImpl> implements DiagnosticSetting, DiagnosticSetting.Definition, DiagnosticSetting.Update { private final ClientLogger logger = new ClientLogger(getClass()); public static final String DIAGNOSTIC_SETTINGS_URI = "/providers/microsoft.insights/diagnosticSettings/"; private String resourceId; private TreeMap<String, MetricSettings> metricSet; private TreeMap<String, LogSettings> logSet; private TreeMap<String, LogSettings> logCategoryGroupSet; private final MonitorManager myManager; DiagnosticSettingImpl( String name, DiagnosticSettingsResourceInner innerModel, final MonitorManager monitorManager) { super(name, innerModel); this.myManager = monitorManager; initializeSets(); } @Override public DiagnosticSettingImpl withResource(String resourceId) { this.resourceId = resourceId; return this; } @Override public DiagnosticSettingImpl withStorageAccount(String storageAccountId) { this.innerModel().withStorageAccountId(storageAccountId); return this; } @Override public DiagnosticSettingImpl withLogAnalytics(String workspaceId) { this.innerModel().withWorkspaceId(workspaceId); return this; } @Override public DiagnosticSettingImpl withoutLogAnalytics() { this.innerModel().withWorkspaceId(null); return this; } @Override public DiagnosticSettingImpl withoutStorageAccount() { this.innerModel().withStorageAccountId(null); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId) { this.innerModel().withEventHubAuthorizationRuleId(eventHubAuthorizationRuleId); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId, String eventHubName) { this.withEventHub(eventHubAuthorizationRuleId); this.innerModel().withEventHubName(eventHubName); return this; } @Override public DiagnosticSettingImpl withoutEventHub() { this.innerModel().withEventHubAuthorizationRuleId(null); this.innerModel().withEventHubName(null); return this; } @Override public DiagnosticSettingImpl withMetric(String category, Duration timeGrain, int retentionDays) { MetricSettings nm = new MetricSettings(); nm.withCategory(category); nm.withEnabled(true); nm.withRetentionPolicy(new RetentionPolicy()); nm.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nm.retentionPolicy().withEnabled(true); } nm.withTimeGrain(timeGrain); this.metricSet.put(category, nm); return this; } @Override public DiagnosticSettingImpl withLog(String category, int retentionDays) { LogSettings nl = new LogSettings(); nl.withCategory(category); nl.withEnabled(true); nl.withRetentionPolicy(new RetentionPolicy()); nl.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nl.retentionPolicy().withEnabled(true); } this.logSet.put(category, nl); return this; } @Override public DiagnosticSettingImpl withLogsAndMetrics( List<DiagnosticSettingsCategory> categories, Duration timeGrain, int retentionDays) { for (DiagnosticSettingsCategory dsc : categories) { if (dsc.type() == CategoryType.METRICS) { this.withMetric(dsc.name(), timeGrain, retentionDays); } else if (dsc.type() == CategoryType.LOGS) { this.withLog(dsc.name(), retentionDays); } else { throw logger.logExceptionAsError( new UnsupportedOperationException(dsc.type().toString() + " is unsupported.")); } } return this; } @Override public DiagnosticSettingImpl withoutMetric(String category) { this.metricSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLog(String category) { this.logSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLogs() { this.logSet.clear(); return this; } @Override public DiagnosticSettingImpl withoutMetrics() { this.metricSet.clear(); return this; } @Override public String id() { return this.innerModel().id(); } @Override public String resourceId() { return this.resourceId; } @Override public String storageAccountId() { return this.innerModel().storageAccountId(); } @Override public String eventHubAuthorizationRuleId() { return this.innerModel().eventHubAuthorizationRuleId(); } @Override public String eventHubName() { return this.innerModel().eventHubName(); } @Override public List<MetricSettings> metrics() { if (this.innerModel().metrics() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().metrics()); } @Override public List<LogSettings> logs() { if (this.innerModel().logs() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().logs()); } @Override public String workspaceId() { return this.innerModel().workspaceId(); } @Override public MonitorManager manager() { return this.myManager; } @Override public boolean isInCreateMode() { return this.innerModel().id() == null; } @Override @Override protected Mono<DiagnosticSettingsResourceInner> getInnerAsync() { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(this.resourceId, this.name()); } @Override public void setInner(DiagnosticSettingsResourceInner inner) { super.setInner(inner); initializeSets(); this.metricSet.clear(); this.logSet.clear(); if (!isInCreateMode()) { this.resourceId = inner .id() .substring( 0, this.innerModel().id().length() - (DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI + this.innerModel().name()).length()); for (MetricSettings ms : this.metrics()) { if (ms.category() != null) { this.metricSet.put(ms.category(), ms); } } for (LogSettings ls : this.logs()) { if (ls.category() != null) { this.logSet.put(ls.category(), ls); } else if (ls.categoryGroup() != null) { this.logCategoryGroupSet.put(ls.categoryGroup(), ls); } } } } private void initializeSets() { if (this.metricSet == null) { this.metricSet = new TreeMap<>(); } if (this.logSet == null) { this.logSet = new TreeMap<>(); } if (this.logCategoryGroupSet == null) { this.logCategoryGroupSet = new TreeMap<>(); } } }
class DiagnosticSettingImpl extends CreatableUpdatableImpl<DiagnosticSetting, DiagnosticSettingsResourceInner, DiagnosticSettingImpl> implements DiagnosticSetting, DiagnosticSetting.Definition, DiagnosticSetting.Update { private final ClientLogger logger = new ClientLogger(getClass()); public static final String DIAGNOSTIC_SETTINGS_URI = "/providers/microsoft.insights/diagnosticSettings/"; private String resourceId; private TreeMap<String, MetricSettings> metricSet; private TreeMap<String, LogSettings> logSet; private TreeMap<String, LogSettings> logCategoryGroupSet; private final MonitorManager myManager; DiagnosticSettingImpl( String name, DiagnosticSettingsResourceInner innerModel, final MonitorManager monitorManager) { super(name, innerModel); this.myManager = monitorManager; initializeSets(); } @Override public DiagnosticSettingImpl withResource(String resourceId) { this.resourceId = resourceId; return this; } @Override public DiagnosticSettingImpl withStorageAccount(String storageAccountId) { this.innerModel().withStorageAccountId(storageAccountId); return this; } @Override public DiagnosticSettingImpl withLogAnalytics(String workspaceId) { this.innerModel().withWorkspaceId(workspaceId); return this; } @Override public DiagnosticSettingImpl withoutLogAnalytics() { this.innerModel().withWorkspaceId(null); return this; } @Override public DiagnosticSettingImpl withoutStorageAccount() { this.innerModel().withStorageAccountId(null); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId) { this.innerModel().withEventHubAuthorizationRuleId(eventHubAuthorizationRuleId); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId, String eventHubName) { this.withEventHub(eventHubAuthorizationRuleId); this.innerModel().withEventHubName(eventHubName); return this; } @Override public DiagnosticSettingImpl withoutEventHub() { this.innerModel().withEventHubAuthorizationRuleId(null); this.innerModel().withEventHubName(null); return this; } @Override public DiagnosticSettingImpl withMetric(String category, Duration timeGrain, int retentionDays) { MetricSettings nm = new MetricSettings(); nm.withCategory(category); nm.withEnabled(true); nm.withRetentionPolicy(new RetentionPolicy()); nm.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nm.retentionPolicy().withEnabled(true); } nm.withTimeGrain(timeGrain); this.metricSet.put(category, nm); return this; } @Override public DiagnosticSettingImpl withLog(String category, int retentionDays) { LogSettings nl = new LogSettings(); nl.withCategory(category); nl.withEnabled(true); nl.withRetentionPolicy(new RetentionPolicy()); nl.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nl.retentionPolicy().withEnabled(true); } this.logSet.put(category, nl); return this; } @Override public DiagnosticSettingImpl withLogsAndMetrics( List<DiagnosticSettingsCategory> categories, Duration timeGrain, int retentionDays) { for (DiagnosticSettingsCategory dsc : categories) { if (dsc.type() == CategoryType.METRICS) { this.withMetric(dsc.name(), timeGrain, retentionDays); } else if (dsc.type() == CategoryType.LOGS) { this.withLog(dsc.name(), retentionDays); } else { throw logger.logExceptionAsError( new UnsupportedOperationException(dsc.type().toString() + " is unsupported.")); } } return this; } @Override public DiagnosticSettingImpl withoutMetric(String category) { this.metricSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLog(String category) { this.logSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLogs() { this.logSet.clear(); return this; } @Override public DiagnosticSettingImpl withoutMetrics() { this.metricSet.clear(); return this; } @Override public String id() { return this.innerModel().id(); } @Override public String resourceId() { return this.resourceId; } @Override public String storageAccountId() { return this.innerModel().storageAccountId(); } @Override public String eventHubAuthorizationRuleId() { return this.innerModel().eventHubAuthorizationRuleId(); } @Override public String eventHubName() { return this.innerModel().eventHubName(); } @Override public List<MetricSettings> metrics() { if (this.innerModel().metrics() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().metrics()); } @Override public List<LogSettings> logs() { if (this.innerModel().logs() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().logs()); } @Override public String workspaceId() { return this.innerModel().workspaceId(); } @Override public MonitorManager manager() { return this.myManager; } @Override public boolean isInCreateMode() { return this.innerModel().id() == null; } @Override @Override protected Mono<DiagnosticSettingsResourceInner> getInnerAsync() { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(this.resourceId, this.name()); } @Override public void setInner(DiagnosticSettingsResourceInner inner) { super.setInner(inner); initializeSets(); this.metricSet.clear(); this.logSet.clear(); if (!isInCreateMode()) { this.resourceId = inner .id() .substring( 0, this.innerModel().id().length() - (DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI + this.innerModel().name()).length()); for (MetricSettings ms : this.metrics()) { if (ms.category() != null) { this.metricSet.put(ms.category(), ms); } } for (LogSettings ls : this.logs()) { if (ls.category() != null) { this.logSet.put(ls.category(), ls); } else if (ls.categoryGroup() != null) { this.logCategoryGroupSet.put(ls.categoryGroup(), ls); } } } } private void initializeSets() { if (this.metricSet == null) { this.metricSet = new TreeMap<>(); } if (this.logSet == null) { this.logSet = new TreeMap<>(); } if (this.logCategoryGroupSet == null) { this.logCategoryGroupSet = new TreeMap<>(); } } }
I believe metrics are in `metricsSet`? https://github.com/Azure/azure-sdk-for-java/blob/6fc1ec62fe97589c512dc7b1193f1ad5472d8d53/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/DiagnosticSettingImpl.java#L106 It's ok, not hurting to have the deduplication.
public Mono<DiagnosticSetting> createResourceAsync() { this.innerModel() .withLogs(new ArrayList<>( Stream.concat(logSet.values().stream(), logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList()))); this.innerModel().withMetrics(new ArrayList<>(metricSet.values())); return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .createOrUpdateAsync(this.resourceId, this.name(), this.innerModel()) .map(innerToFluentMap(this)); }
logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList())));
public Mono<DiagnosticSetting> createResourceAsync() { this.innerModel() .withLogs(new ArrayList<>( Stream.concat(logSet.values().stream(), logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList()))); this.innerModel().withMetrics(new ArrayList<>(metricSet.values())); return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .createOrUpdateAsync(this.resourceId, this.name(), this.innerModel()) .map(innerToFluentMap(this)); }
class DiagnosticSettingImpl extends CreatableUpdatableImpl<DiagnosticSetting, DiagnosticSettingsResourceInner, DiagnosticSettingImpl> implements DiagnosticSetting, DiagnosticSetting.Definition, DiagnosticSetting.Update { private final ClientLogger logger = new ClientLogger(getClass()); public static final String DIAGNOSTIC_SETTINGS_URI = "/providers/microsoft.insights/diagnosticSettings/"; private String resourceId; private TreeMap<String, MetricSettings> metricSet; private TreeMap<String, LogSettings> logSet; private TreeMap<String, LogSettings> logCategoryGroupSet; private final MonitorManager myManager; DiagnosticSettingImpl( String name, DiagnosticSettingsResourceInner innerModel, final MonitorManager monitorManager) { super(name, innerModel); this.myManager = monitorManager; initializeSets(); } @Override public DiagnosticSettingImpl withResource(String resourceId) { this.resourceId = resourceId; return this; } @Override public DiagnosticSettingImpl withStorageAccount(String storageAccountId) { this.innerModel().withStorageAccountId(storageAccountId); return this; } @Override public DiagnosticSettingImpl withLogAnalytics(String workspaceId) { this.innerModel().withWorkspaceId(workspaceId); return this; } @Override public DiagnosticSettingImpl withoutLogAnalytics() { this.innerModel().withWorkspaceId(null); return this; } @Override public DiagnosticSettingImpl withoutStorageAccount() { this.innerModel().withStorageAccountId(null); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId) { this.innerModel().withEventHubAuthorizationRuleId(eventHubAuthorizationRuleId); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId, String eventHubName) { this.withEventHub(eventHubAuthorizationRuleId); this.innerModel().withEventHubName(eventHubName); return this; } @Override public DiagnosticSettingImpl withoutEventHub() { this.innerModel().withEventHubAuthorizationRuleId(null); this.innerModel().withEventHubName(null); return this; } @Override public DiagnosticSettingImpl withMetric(String category, Duration timeGrain, int retentionDays) { MetricSettings nm = new MetricSettings(); nm.withCategory(category); nm.withEnabled(true); nm.withRetentionPolicy(new RetentionPolicy()); nm.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nm.retentionPolicy().withEnabled(true); } nm.withTimeGrain(timeGrain); this.metricSet.put(category, nm); return this; } @Override public DiagnosticSettingImpl withLog(String category, int retentionDays) { LogSettings nl = new LogSettings(); nl.withCategory(category); nl.withEnabled(true); nl.withRetentionPolicy(new RetentionPolicy()); nl.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nl.retentionPolicy().withEnabled(true); } this.logSet.put(category, nl); return this; } @Override public DiagnosticSettingImpl withLogsAndMetrics( List<DiagnosticSettingsCategory> categories, Duration timeGrain, int retentionDays) { for (DiagnosticSettingsCategory dsc : categories) { if (dsc.type() == CategoryType.METRICS) { this.withMetric(dsc.name(), timeGrain, retentionDays); } else if (dsc.type() == CategoryType.LOGS) { this.withLog(dsc.name(), retentionDays); } else { throw logger.logExceptionAsError( new UnsupportedOperationException(dsc.type().toString() + " is unsupported.")); } } return this; } @Override public DiagnosticSettingImpl withoutMetric(String category) { this.metricSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLog(String category) { this.logSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLogs() { this.logSet.clear(); return this; } @Override public DiagnosticSettingImpl withoutMetrics() { this.metricSet.clear(); return this; } @Override public String id() { return this.innerModel().id(); } @Override public String resourceId() { return this.resourceId; } @Override public String storageAccountId() { return this.innerModel().storageAccountId(); } @Override public String eventHubAuthorizationRuleId() { return this.innerModel().eventHubAuthorizationRuleId(); } @Override public String eventHubName() { return this.innerModel().eventHubName(); } @Override public List<MetricSettings> metrics() { if (this.innerModel().metrics() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().metrics()); } @Override public List<LogSettings> logs() { if (this.innerModel().logs() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().logs()); } @Override public String workspaceId() { return this.innerModel().workspaceId(); } @Override public MonitorManager manager() { return this.myManager; } @Override public boolean isInCreateMode() { return this.innerModel().id() == null; } @Override @Override protected Mono<DiagnosticSettingsResourceInner> getInnerAsync() { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(this.resourceId, this.name()); } @Override public void setInner(DiagnosticSettingsResourceInner inner) { super.setInner(inner); initializeSets(); this.metricSet.clear(); this.logSet.clear(); if (!isInCreateMode()) { this.resourceId = inner .id() .substring( 0, this.innerModel().id().length() - (DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI + this.innerModel().name()).length()); for (MetricSettings ms : this.metrics()) { if (ms.category() != null) { this.metricSet.put(ms.category(), ms); } } for (LogSettings ls : this.logs()) { if (ls.category() != null) { this.logSet.put(ls.category(), ls); } else if (ls.categoryGroup() != null) { this.logCategoryGroupSet.put(ls.categoryGroup(), ls); } } } } private void initializeSets() { if (this.metricSet == null) { this.metricSet = new TreeMap<>(); } if (this.logSet == null) { this.logSet = new TreeMap<>(); } if (this.logCategoryGroupSet == null) { this.logCategoryGroupSet = new TreeMap<>(); } } }
class DiagnosticSettingImpl extends CreatableUpdatableImpl<DiagnosticSetting, DiagnosticSettingsResourceInner, DiagnosticSettingImpl> implements DiagnosticSetting, DiagnosticSetting.Definition, DiagnosticSetting.Update { private final ClientLogger logger = new ClientLogger(getClass()); public static final String DIAGNOSTIC_SETTINGS_URI = "/providers/microsoft.insights/diagnosticSettings/"; private String resourceId; private TreeMap<String, MetricSettings> metricSet; private TreeMap<String, LogSettings> logSet; private TreeMap<String, LogSettings> logCategoryGroupSet; private final MonitorManager myManager; DiagnosticSettingImpl( String name, DiagnosticSettingsResourceInner innerModel, final MonitorManager monitorManager) { super(name, innerModel); this.myManager = monitorManager; initializeSets(); } @Override public DiagnosticSettingImpl withResource(String resourceId) { this.resourceId = resourceId; return this; } @Override public DiagnosticSettingImpl withStorageAccount(String storageAccountId) { this.innerModel().withStorageAccountId(storageAccountId); return this; } @Override public DiagnosticSettingImpl withLogAnalytics(String workspaceId) { this.innerModel().withWorkspaceId(workspaceId); return this; } @Override public DiagnosticSettingImpl withoutLogAnalytics() { this.innerModel().withWorkspaceId(null); return this; } @Override public DiagnosticSettingImpl withoutStorageAccount() { this.innerModel().withStorageAccountId(null); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId) { this.innerModel().withEventHubAuthorizationRuleId(eventHubAuthorizationRuleId); return this; } @Override public DiagnosticSettingImpl withEventHub(String eventHubAuthorizationRuleId, String eventHubName) { this.withEventHub(eventHubAuthorizationRuleId); this.innerModel().withEventHubName(eventHubName); return this; } @Override public DiagnosticSettingImpl withoutEventHub() { this.innerModel().withEventHubAuthorizationRuleId(null); this.innerModel().withEventHubName(null); return this; } @Override public DiagnosticSettingImpl withMetric(String category, Duration timeGrain, int retentionDays) { MetricSettings nm = new MetricSettings(); nm.withCategory(category); nm.withEnabled(true); nm.withRetentionPolicy(new RetentionPolicy()); nm.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nm.retentionPolicy().withEnabled(true); } nm.withTimeGrain(timeGrain); this.metricSet.put(category, nm); return this; } @Override public DiagnosticSettingImpl withLog(String category, int retentionDays) { LogSettings nl = new LogSettings(); nl.withCategory(category); nl.withEnabled(true); nl.withRetentionPolicy(new RetentionPolicy()); nl.retentionPolicy().withDays(retentionDays); if (retentionDays > 0) { nl.retentionPolicy().withEnabled(true); } this.logSet.put(category, nl); return this; } @Override public DiagnosticSettingImpl withLogsAndMetrics( List<DiagnosticSettingsCategory> categories, Duration timeGrain, int retentionDays) { for (DiagnosticSettingsCategory dsc : categories) { if (dsc.type() == CategoryType.METRICS) { this.withMetric(dsc.name(), timeGrain, retentionDays); } else if (dsc.type() == CategoryType.LOGS) { this.withLog(dsc.name(), retentionDays); } else { throw logger.logExceptionAsError( new UnsupportedOperationException(dsc.type().toString() + " is unsupported.")); } } return this; } @Override public DiagnosticSettingImpl withoutMetric(String category) { this.metricSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLog(String category) { this.logSet.remove(category); return this; } @Override public DiagnosticSettingImpl withoutLogs() { this.logSet.clear(); return this; } @Override public DiagnosticSettingImpl withoutMetrics() { this.metricSet.clear(); return this; } @Override public String id() { return this.innerModel().id(); } @Override public String resourceId() { return this.resourceId; } @Override public String storageAccountId() { return this.innerModel().storageAccountId(); } @Override public String eventHubAuthorizationRuleId() { return this.innerModel().eventHubAuthorizationRuleId(); } @Override public String eventHubName() { return this.innerModel().eventHubName(); } @Override public List<MetricSettings> metrics() { if (this.innerModel().metrics() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().metrics()); } @Override public List<LogSettings> logs() { if (this.innerModel().logs() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.innerModel().logs()); } @Override public String workspaceId() { return this.innerModel().workspaceId(); } @Override public MonitorManager manager() { return this.myManager; } @Override public boolean isInCreateMode() { return this.innerModel().id() == null; } @Override @Override protected Mono<DiagnosticSettingsResourceInner> getInnerAsync() { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(this.resourceId, this.name()); } @Override public void setInner(DiagnosticSettingsResourceInner inner) { super.setInner(inner); initializeSets(); this.metricSet.clear(); this.logSet.clear(); if (!isInCreateMode()) { this.resourceId = inner .id() .substring( 0, this.innerModel().id().length() - (DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI + this.innerModel().name()).length()); for (MetricSettings ms : this.metrics()) { if (ms.category() != null) { this.metricSet.put(ms.category(), ms); } } for (LogSettings ls : this.logs()) { if (ls.category() != null) { this.logSet.put(ls.category(), ls); } else if (ls.categoryGroup() != null) { this.logCategoryGroupSet.put(ls.categoryGroup(), ls); } } } } private void initializeSets() { if (this.metricSet == null) { this.metricSet = new TreeMap<>(); } if (this.logSet == null) { this.logSet = new TreeMap<>(); } if (this.logCategoryGroupSet == null) { this.logCategoryGroupSet = new TreeMap<>(); } } }
Only the necessary basic settings have been retained in the new version.
public void testCreateFluidRelayServer() { FluidRelayServer server = null; try { String serverName = "server" + randomPadding(); server = fluidRelayManager.fluidRelayServers() .define(serverName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withIdentity(new Identity().withType(ResourceIdentityType.NONE)) .withStoragesku(StorageSku.STANDARD) .withProvisioningState(ProvisioningState.SUCCEEDED) .create(); server.refresh(); Assertions.assertEquals(server.name(), serverName); Assertions.assertEquals(server.name(), fluidRelayManager.fluidRelayServers().getById(server.id()).name()); Assertions.assertTrue(fluidRelayManager.fluidRelayServers().list().stream().count() > 0); } finally { if (server != null) { fluidRelayManager.fluidRelayServers().deleteById(server.id()); } } }
.withProvisioningState(ProvisioningState.SUCCEEDED)
public void testCreateFluidRelayServer() { FluidRelayServer server = null; try { String serverName = "server" + randomPadding(); server = fluidRelayManager.fluidRelayServers() .define(serverName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .create(); server.refresh(); Assertions.assertEquals(server.name(), serverName); Assertions.assertEquals(server.name(), fluidRelayManager.fluidRelayServers().getById(server.id()).name()); Assertions.assertTrue(fluidRelayManager.fluidRelayServers().list().stream().count() > 0); } finally { if (server != null) { fluidRelayManager.fluidRelayServers().deleteById(server.id()); } } }
class FluidRelayManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private FluidRelayManager fluidRelayManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); fluidRelayManager = FluidRelayManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class FluidRelayManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private FluidRelayManager fluidRelayManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); fluidRelayManager = FluidRelayManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
I don't think user need to set this. Could you try create without it?
public void testCreateFluidRelayServer() { FluidRelayServer server = null; try { String serverName = "server" + randomPadding(); server = fluidRelayManager.fluidRelayServers() .define(serverName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withIdentity(new Identity().withType(ResourceIdentityType.NONE)) .withStoragesku(StorageSku.STANDARD) .withProvisioningState(ProvisioningState.SUCCEEDED) .create(); server.refresh(); Assertions.assertEquals(server.name(), serverName); Assertions.assertEquals(server.name(), fluidRelayManager.fluidRelayServers().getById(server.id()).name()); Assertions.assertTrue(fluidRelayManager.fluidRelayServers().list().stream().count() > 0); } finally { if (server != null) { fluidRelayManager.fluidRelayServers().deleteById(server.id()); } } }
.withProvisioningState(ProvisioningState.SUCCEEDED)
public void testCreateFluidRelayServer() { FluidRelayServer server = null; try { String serverName = "server" + randomPadding(); server = fluidRelayManager.fluidRelayServers() .define(serverName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .create(); server.refresh(); Assertions.assertEquals(server.name(), serverName); Assertions.assertEquals(server.name(), fluidRelayManager.fluidRelayServers().getById(server.id()).name()); Assertions.assertTrue(fluidRelayManager.fluidRelayServers().list().stream().count() > 0); } finally { if (server != null) { fluidRelayManager.fluidRelayServers().deleteById(server.id()); } } }
class FluidRelayManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private FluidRelayManager fluidRelayManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); fluidRelayManager = FluidRelayManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class FluidRelayManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private FluidRelayManager fluidRelayManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); fluidRelayManager = FluidRelayManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Remove `return` here because when using testproxy, `interceptorManager.getRecordedData()` will be `null`. If `return` directly, when running in playback mode, below logics to initialize clients will be skiped. There will be nullpointer error since the client is not initialized when running tests in playback. ![image](https://github.com/Azure/azure-sdk-for-java/assets/87355844/2b87b0c0-fb5e-48d5-98ae-32239c430ac9)
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( null, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } initializeClients(httpPipeline, testProfile); }
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
I assume these are duplicate code? Either use a common base, or move them to util class.
public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; }
}
public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); } initializeClients(httpPipeline, testProfile); } /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); } /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
What's the difference?
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); } initializeClients(httpPipeline, testProfile); }
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
I assume this also duplicate code?
protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); }
}
protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); } initializeClients(httpPipeline, testProfile); } /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); } /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
I am fine with some duplicate code, but not lots of them.
public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; }
}
public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); } initializeClients(httpPipeline, testProfile); } /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); } /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
Currently ResourceManagerTestProxyTestBase is just a copy of ResourceManagerTestBase, with updates in 'code change' section in description to fit in TestProxy. ![image](https://github.com/Azure/azure-sdk-for-java/assets/87355844/159f49f3-1b04-483f-b6e1-2285271a2c75) Let me try to refine the code to make it easier to reuse the code in ResourceManagerTestBase and easier to see the difference.
public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; }
}
public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); } initializeClients(httpPipeline, testProfile); } /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); } /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
Since this is TextProxyTestBase, I take `interceptorManager.getRecordedData()` is always `null`, and `skipInPlayback()` is always called? And why do we want `skipInPlayback()` always called? (regardless whether the test want to skip in playback or not)
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( null, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } initializeClients(httpPipeline, testProfile); }
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
`isSkipInPlayback = true` seems meaning it does not clean up the resource after test complete?
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( null, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } initializeClients(httpPipeline, testProfile); }
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
> `isSkipInPlayback = true` seems meaning it does not clean up the resource after test complete? Yes, if we set to true, it will not do test resource clean up calls. Previously I think it is playback mode, there is no need to do resource clean up. But to be consistent with previous logic, we can do resouce clean up as well, that is to delete below whole part. What do you think? ```java if (interceptorManager.getRecordedData() == null) { skipInPlayback(); return; } ```
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( null, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } initializeClients(httpPipeline, testProfile); }
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
Yeah, you can do this. Later we may get to test case with `@DoNotRecord(skipInPlayback = true)`, which may have problem under TestProxy setting (I kind of assume code here was to handle that, but not sure). You can handle that later.
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( null, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } initializeClients(httpPipeline, testProfile); }
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
`@DoNotRecord(skipInPlayback = true)` -> there is this case in resources. I will delete this part logic and try on playback and record mode.
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { if (interceptorManager.getRecordedData() == null) { skipInPlayback(); } testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); httpPipeline = buildHttpPipeline( null, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); textReplacementRules.put(PLAYBACK_URI_BASE + "1234", PLAYBACK_URI); addTextReplacementRules(textReplacementRules); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(new TextReplacementPolicy(interceptorManager.getRecordedData(), textReplacementRules)); policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); textReplacementRules.put(testProfile.getSubscriptionId(), ZERO_SUBSCRIPTION); textReplacementRules.put(testProfile.getTenantId(), ZERO_TENANT); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getResourceManagerEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put(Pattern.quote(AzureEnvironment.AZURE.getMicrosoftGraphEndpoint()), PLAYBACK_URI + "/"); textReplacementRules.put("https: textReplacementRules.put("https: addTextReplacementRules(textReplacementRules); } initializeClients(httpPipeline, testProfile); }
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
One corner case would be service does not set `retry-after` header. Though I thought SDK will set the default LRO poll interval to something like 0 during playback, so we are likely fine.
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; Map<String, String> textReplacementRules = new HashMap<>(); String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL))); interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER))); } initializeClients(httpPipeline, testProfile); }
interceptorManager.addSanitizers(Arrays.asList(new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER)));
protected void beforeTest() { TokenCredential credential; HttpPipeline httpPipeline; String logLevel = Configuration.getGlobalConfiguration().get(AZURE_TEST_LOG_LEVEL); HttpLogDetailLevel httpLogDetailLevel; try { httpLogDetailLevel = HttpLogDetailLevel.valueOf(logLevel); } catch (Exception e) { if (isPlaybackMode()) { httpLogDetailLevel = HttpLogDetailLevel.NONE; LOGGER.error("Environment variable '{}' has not been set yet. Using 'NONE' for PLAYBACK.", AZURE_TEST_LOG_LEVEL); } else { httpLogDetailLevel = HttpLogDetailLevel.BODY_AND_HEADERS; LOGGER.error("Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", AZURE_TEST_LOG_LEVEL); } } if (httpLogDetailLevel == HttpLogDetailLevel.NONE) { try { System.setOut(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); System.setErr(new PrintStream(EMPTY_OUTPUT_STREAM, false, Charset.defaultCharset().name())); } catch (UnsupportedEncodingException e) { } } if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List<HttpPipelinePolicy> policies = new ArrayList<>(); httpPipeline = buildHttpPipeline( request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")))); addSanitizers(); } } else { if (System.getenv(AZURE_AUTH_LOCATION) != null) { final File credFile = new File(System.getenv(AZURE_AUTH_LOCATION)); try { testAuthFile = AuthFile.parse(credFile); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot parse auth file. Please check file format.", e)); } credential = testAuthFile.getCredential(); testProfile = new AzureProfile(testAuthFile.getTenantId(), testAuthFile.getSubscriptionId(), testAuthFile.getEnvironment()); } else { Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); if (clientId == null || tenantId == null || clientSecret == null || subscriptionId == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("When running tests in record mode either 'AZURE_AUTH_LOCATION' or 'AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID' needs to be set")); } credential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new TimeoutPolicy(Duration.ofMinutes(1))); if (!interceptorManager.isLiveMode() && !testContextManager.doNotRecordTest()) { policies.add(this.interceptorManager.getRecordPolicy()); addSanitizers(); } if (httpLogDetailLevel == HttpLogDetailLevel.BODY_AND_HEADERS) { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } httpPipeline = buildHttpPipeline( credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } private void addTextReplacementRules(Map<String, String> rules) { for (Map.Entry<String, String> entry : rules.entrySet()) { interceptorManager.addTextReplacementRule(entry.getKey(), entry.getValue()); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
class ResourceManagerTestProxyTestBase extends TestProxyTestBase { private static final String ZERO_UUID = "00000000-0000-0000-0000-000000000000"; private static final String ZERO_SUBSCRIPTION = ZERO_UUID; private static final String ZERO_TENANT = ZERO_UUID; private static final String PLAYBACK_URI_BASE = "https: private static final String AZURE_AUTH_LOCATION = "AZURE_AUTH_LOCATION"; private static final String AZURE_TEST_LOG_LEVEL = "AZURE_TEST_LOG_LEVEL"; private static final String HTTPS_PROXY_HOST = "https.proxyHost"; private static final String HTTPS_PROXY_PORT = "https.proxyPort"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String USE_SYSTEM_PROXY = "java.net.useSystemProxies"; private static final String VALUE_TRUE = "true"; private static final String PLAYBACK_URI = PLAYBACK_URI_BASE + "1234"; private static final AzureProfile PLAYBACK_PROFILE = new AzureProfile( ZERO_TENANT, ZERO_SUBSCRIPTION, new AzureEnvironment(Arrays.stream(AzureEnvironment.Endpoint.values()) .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI))) ); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { } }; private static final ClientLogger LOGGER = new ClientLogger(ResourceManagerTestProxyTestBase.class); private AzureProfile testProfile; private AuthFile testAuthFile; private boolean isSkipInPlayback; /** * Sets upper bound execution timeout for each @Test method. * {@link org.junit.jupiter.api.Timeout} annotation on test methods will only narrow the timeout, not affecting the upper * bound. */ @RegisterExtension final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(30)); /** * Generates a random resource name. * * @param prefix Prefix for the resource name. * @param maxLen Maximum length of the resource name. * @return A randomly generated resource name with a given prefix and maximum length. */ protected String generateRandomResourceName(String prefix, int maxLen) { return testResourceNamer.randomName(prefix, maxLen); } /** * @return A randomly generated UUID. */ protected String generateRandomUuid() { return testResourceNamer.randomUuid(); } /** * @return random password */ public static String password() { String password = new ResourceNamer("").randomName("Pa5$", 12); LOGGER.info("Password: {}", password); return password; } private static String sshPublicKey; /** * @return an SSH public key */ public static String sshPublicKey() { if (sshPublicKey == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes(StandardCharsets.US_ASCII).length); dos.write("ssh-rsa".getBytes(StandardCharsets.US_ASCII)); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.getEncoder().encode(byteOs.toByteArray()), StandardCharsets.US_ASCII); sshPublicKey = "ssh-rsa " + publicKeyEncoded; } catch (NoSuchAlgorithmException | IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("failed to generate ssh key", e)); } } return sshPublicKey; } /** * Loads a credential from file. * * @return A credential loaded from a file. */ protected TokenCredential credentialFromFile() { return testAuthFile.getCredential(); } /** * Loads a client ID from file. * * @return A client ID loaded from a file. */ protected String clientIdFromFile() { String clientId = testAuthFile == null ? null : testAuthFile.getClientId(); return testResourceNamer.recordValueFromConfig(clientId); } /** * @return The test profile. */ protected AzureProfile profile() { return testProfile; } /** * @return Whether the test mode is {@link TestMode */ protected boolean isPlaybackMode() { return getTestMode() == TestMode.PLAYBACK; } /** * @return Whether the test should be skipped in playback. */ protected boolean skipInPlayback() { if (isPlaybackMode()) { isSkipInPlayback = true; } return isSkipInPlayback; } @Override /** * Generates an {@link HttpClient} with a proxy. * * @param clientBuilder The HttpClient builder. * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } if (proxyOptions != null) { clientBuilder.proxy(proxyOptions); } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); List<Proxy> proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { String host = ((InetSocketAddress) proxy.address()).getHostName(); int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); case SOCKS: return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, new InetSocketAddress(host, port))).build(); default: } } } } String host = null; int port = 0; if (System.getProperty(HTTPS_PROXY_HOST) != null && System.getProperty(HTTPS_PROXY_PORT) != null) { host = System.getProperty(HTTPS_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTPS_PROXY_PORT)); } else if (System.getProperty(HTTP_PROXY_HOST) != null && System.getProperty(HTTP_PROXY_PORT) != null) { host = System.getProperty(HTTP_PROXY_HOST); port = Integer.parseInt(System.getProperty(HTTP_PROXY_PORT)); } if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } } catch (URISyntaxException e) { } } return clientBuilder.build(); } @Override protected void afterTest() { if (!isSkipInPlayback) { cleanUpResources(); } } /** * Sets sdk context when running the tests * * @param internalContext the internal runtime context * @param objects the manager classes to change internal context * @param <T> the type of internal context * @throws RuntimeException when field cannot be found or set. */ protected <T> void setInternalContext(T internalContext, Object... objects) { try { for (Object obj : objects) { for (final Field field : obj.getClass().getSuperclass().getDeclaredFields()) { if (field.getName().equals("resourceManager")) { setAccessible(field); Field context = field.get(obj).getClass().getDeclaredField("internalContext"); setAccessible(context); context.set(field.get(obj), internalContext); } } for (Field field : obj.getClass().getDeclaredFields()) { if (field.getName().equals("internalContext")) { setAccessible(field); field.set(obj, internalContext); } else if (field.getName().contains("Manager")) { setAccessible(field); setInternalContext(internalContext, field.get(obj)); } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } private void setAccessible(final AccessibleObject accessibleObject) { Runnable runnable = () -> accessibleObject.setAccessible(true); runnable.run(); } /** * Builds the manager with provided http pipeline and profile in general manner. * * @param manager the class of the manager * @param httpPipeline the http pipeline * @param profile the azure profile * @param <T> the type of the manager * @return the manager instance * @throws RuntimeException when field cannot be found or set. */ protected <T> T buildManager(Class<T> manager, HttpPipeline httpPipeline, AzureProfile profile) { try { Constructor<T> constructor = manager.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass()); setAccessible(constructor); return constructor.newInstance(httpPipeline, profile); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw LOGGER.logExceptionAsError(new RuntimeException(ex)); } } /** * Builds an HttpPipeline. * * @param credential The credentials to use in the pipeline. * @param profile The AzureProfile to use in the pipeline. * @param httpLogOptions The HTTP logging options to use in the pipeline. * @param policies Additional policies to use in the pipeline. * @param httpClient The HttpClient to use in the pipeline. * @return A new constructed HttpPipeline. */ protected abstract HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient); /** * Initializes service clients used in testing. * * @param httpPipeline The HttpPipeline to use in the clients. * @param profile The AzureProfile to use in the clients. */ protected abstract void initializeClients(HttpPipeline httpPipeline, AzureProfile profile); /** * Cleans up resources. */ protected abstract void cleanUpResources(); private void addSanitizers() { interceptorManager.addSanitizers(Arrays.asList( new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL), new TestProxySanitizer("Retry-After", null, "0", TestProxySanitizerType.HEADER) )); } private final class PlaybackTimeoutInterceptor implements InvocationInterceptor { private final Duration duration; private PlaybackTimeoutInterceptor(Supplier<Duration> timeoutSupplier) { Objects.requireNonNull(timeoutSupplier); this.duration = timeoutSupplier.get(); } @Override public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { invocation.proceed(); } } } }
why do we need to add a retry policy in tests? We should have one added by default.
void azureIdentityCredentials(HttpClient httpClient) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(); final TokenCredential tokenCredential = getTokenCredential(); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder(); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient) .addPolicy(new RetryPolicy()); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } final ServiceBusAdministrationAsyncClient client = builder .credential(fullyQualifiedDomainName, tokenCredential) .buildAsyncClient(); StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertNotNull(properties); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } assertEquals(expectedName, properties.getName()); }) .verifyComplete(); }
.addPolicy(new RetryPolicy());
void azureIdentityCredentials(HttpClient httpClient) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(); final TokenCredential tokenCredential; if (interceptorManager.isPlaybackMode()) { tokenCredential = mock(TokenCredential.class); Mockito.when(tokenCredential.getToken(any(TokenRequestContext.class))).thenReturn(Mono.fromCallable(() -> { return new AccessToken("foo-bar", OffsetDateTime.now().plus(Duration.ofMinutes(5))); })); } else { tokenCredential = new DefaultAzureCredentialBuilder().build(); } final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder(); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } final ServiceBusAdministrationAsyncClient client = builder .credential(fullyQualifiedDomainName, tokenCredential) .buildAsyncClient(); StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertNotNull(properties); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } assertEquals(expectedName, properties.getName()); }) .verifyComplete(); }
class ServiceBusAdministrationAsyncClientIntegrationTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(20); @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(10)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } static Stream<Arguments> createHttpClients() { return Stream.of( Arguments.of(new NettyAsyncHttpClientBuilder().build()) ); } /** * Test to connect to the service bus with an azure identity TokenCredential. * com.azure.identity.ClientSecretCredential is used in this test. * ServiceBusSharedKeyCredential doesn't need a specific test method because other tests below * use connection string, which is converted to a ServiceBusSharedKeyCredential internally. */ @ParameterizedTest @MethodSource("createHttpClients") @ParameterizedTest @MethodSource("createHttpClients") void createQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueExistingName(HttpClient httpClient) { final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions options = new CreateQueueOptions(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createQueue(queueName, options)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final String forwardToEntityName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions expected = new CreateQueueOptions() .setForwardTo(forwardToEntityName) .setForwardDeadLetteredMessagesTo(forwardToEntityName); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueAuthorizationRules(HttpClient httpClient) { final String keyName = "test-rule"; final List<AccessRights> accessRights = Collections.singletonList(AccessRights.SEND); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final SharedAccessAuthorizationRule rule = interceptorManager.isPlaybackMode() ? new SharedAccessAuthorizationRule(keyName, "REDACTED", "REDACTED", accessRights) : new SharedAccessAuthorizationRule(keyName, accessRights); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); expected.getAuthorizationRules().add(rule); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); assertAuthorizationRules(expected.getAuthorizationRules(), actual.getAuthorizationRules()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction action = new SqlRuleAction("SET Label = 'test'"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(action) .setFilter(new FalseRuleFilter()); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName, options)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(action.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof FalseRuleFilter); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleDefaults(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName)) .assertNext(contents -> { assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleFilter filter = new SqlRuleFilter("sys.To=@MyParameter OR sys.MessageId IS NULL"); filter.getParameters().put("@MyParameter", "My-Parameter-Value"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(new EmptyRuleAction()) .setFilter(filter); StepVerifier.create(client.createRuleWithResponse(topicName, subscriptionName, ruleName, options)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); final SqlRuleFilter actualFilter = (SqlRuleFilter) contents.getFilter(); assertEquals(filter.getSqlExpression(), actualFilter.getSqlExpression()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 0); final String subscriptionName = testResourceNamer.randomName("sub", 10); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setUserMetadata("some-metadata-for-testing-subscriptions"); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionExistingName(HttpClient httpClient) { final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createSubscription(topicName, subscriptionName)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 3); final String subscriptionName = testResourceNamer.randomName("sub", 50); final String forwardToTopic = getEntityName(getTopicBaseName(), 4); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setForwardTo(forwardToTopic) .setForwardDeadLetteredMessagesTo(forwardToTopic); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } }) .expectComplete() .verify(TIMEOUT); } @ParameterizedTest @MethodSource("createHttpClients") void createTopicWithResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("test", 10); final CreateTopicOptions expected = new CreateTopicOptions() .setMaxSizeInMegabytes(2048L) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing-topic"); StepVerifier.create(client.createTopicWithResponse(topicName, expected)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final TopicProperties actual = response.getValue(); assertEquals(topicName, actual.getName()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(actual); assertEquals(0, runtimeProperties.getSubscriptionCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("sub", 10); client.createQueue(queueName) .onErrorResume(ResourceExistsException.class, e -> Mono.empty()) .block(TIMEOUT); StepVerifier.create(client.deleteQueue(queueName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule-", 11); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); StepVerifier.create(client.deleteRule(topicName, subscriptionName, ruleName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); final String subscriptionName = testResourceNamer.randomName("sub", 7); client.createTopic(topicName).block(TIMEOUT); client.createSubscription(topicName, subscriptionName).block(TIMEOUT); StepVerifier.create(client.deleteSubscription(topicName, subscriptionName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); client.createTopic(topicName).block(TIMEOUT); StepVerifier.create(client.deleteTopic(topicName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueue(queueName)) .assertNext(queueDescription -> { assertEquals(queueName, queueDescription.getName()); assertFalse(queueDescription.isPartitioningEnabled()); assertFalse(queueDescription.isSessionRequired()); assertNotNull(queueDescription.getLockDuration()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(queueDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getNamespace(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertEquals(NamespaceType.MESSAGING, properties.getNamespaceType()); assertEquals(expectedName, properties.getName()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueue(queueName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueueRuntimeProperties(queueName)) .assertNext(RuntimeProperties -> { assertEquals(queueName, RuntimeProperties.getName()); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.getRuleWithResponse(topicName, subscriptionName, ruleName)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.isSessionRequired()); assertNotNull(description.getLockDuration()); final SubscriptionRuntimeProperties runtimeProperties = new SubscriptionRuntimeProperties(description); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.getTotalMessageCount() >= 0); assertEquals(0, description.getActiveMessageCount()); assertEquals(0, description.getTransferDeadLetterMessageCount()); assertEquals(0, description.getTransferMessageCount()); assertTrue(description.getDeadLetterMessageCount() >= 0); assertNotNull(description.getCreatedAt()); assertTrue(nowUtc.isAfter(description.getCreatedAt())); assertNotNull(description.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopic(topicName)) .assertNext(topicDescription -> { assertEquals(topicName, topicDescription.getName()); assertTrue(topicDescription.isBatchedOperationsEnabled()); assertFalse(topicDescription.isDuplicateDetectionRequired()); assertNotNull(topicDescription.getDuplicateDetectionHistoryTimeWindow()); assertNotNull(topicDescription.getDefaultMessageTimeToLive()); assertFalse(topicDescription.isPartitioningEnabled()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(topicDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopic(topicName)) .consumeErrorWith(error -> { assertTrue(error instanceof ResourceNotFoundException); final ResourceNotFoundException notFoundError = (ResourceNotFoundException) error; final HttpResponse response = notFoundError.getResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); StepVerifier.create(response.getBody()) .verifyComplete(); }) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopicRuntimeProperties(topicName)) .assertNext(RuntimeProperties -> { assertEquals(topicName, RuntimeProperties.getName()); assertTrue(RuntimeProperties.getSubscriptionCount() > 1); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getAccessedAt())); assertEquals(0, RuntimeProperties.getScheduledMessageCount()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimePropertiesUnauthorizedClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final String connectionStringUpdated = connectionString.replace("SharedAccessKey=", "SharedAccessKey=fake-key-"); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionStringUpdated); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient) .addPolicy(new RetryPolicy()); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } final ServiceBusAdministrationAsyncClient client = builder.buildAsyncClient(); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getEntityName(getSubscriptionBaseName(), 2); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .verifyErrorMatches(throwable -> throwable instanceof ClientAuthenticationException); } @ParameterizedTest @MethodSource("createHttpClients") void listRules(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.listRules(topicName, subscriptionName)) .assertNext(response -> { assertEquals(ruleName, response.getName()); assertNotNull(response.getFilter()); assertTrue(response.getFilter() instanceof TrueRuleFilter); assertNotNull(response.getAction()); assertTrue(response.getAction() instanceof EmptyRuleAction); }) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listQueues(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listQueues()) .assertNext(queueDescription -> { assertNotNull(queueDescription.getName()); assertTrue(queueDescription.isBatchedOperationsEnabled()); assertFalse(queueDescription.isDuplicateDetectionRequired()); assertFalse(queueDescription.isPartitioningEnabled()); }) .expectNextCount(9) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listSubscriptions(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.listSubscriptions(topicName)) .assertNext(subscription -> { assertEquals(topicName, subscription.getTopicName()); assertNotNull(subscription.getSubscriptionName()); }) .expectNextCount(1) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listTopics(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listTopics()) .assertNext(topics -> { assertNotNull(topics.getName()); assertTrue(topics.isBatchedOperationsEnabled()); assertFalse(topics.isPartitioningEnabled()); }) .expectNextCount(2) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void updateRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 15); final String topicName = getEntityName(getTopicBaseName(), 12); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction expectedAction = new SqlRuleAction("SET MessageId = 'matching-id'"); final SqlRuleFilter expectedFilter = new SqlRuleFilter("sys.To = 'telemetry-event'"); final RuleProperties existingRule = client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); assertNotNull(existingRule); existingRule.setAction(expectedAction).setFilter(expectedFilter); StepVerifier.create(client.updateRule(topicName, subscriptionName, existingRule)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); assertEquals(expectedFilter.getSqlExpression(), ((SqlRuleFilter) contents.getFilter()).getSqlExpression()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(expectedAction.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); }) .verifyComplete(); } private ServiceBusAdministrationAsyncClient createClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionString); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient) .addPolicy(new RetryPolicy()); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } return builder.buildAsyncClient(); } private TokenCredential getTokenCredential() { final DefaultAzureCredentialBuilder builder = new DefaultAzureCredentialBuilder(); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } return builder.build(); } }
class ServiceBusAdministrationAsyncClientIntegrationTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(20); @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(10)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } static Stream<Arguments> createHttpClients() { return Stream.of( Arguments.of(new NettyAsyncHttpClientBuilder().build()) ); } /** * Test to connect to the service bus with an azure identity TokenCredential. * com.azure.identity.ClientSecretCredential is used in this test. * ServiceBusSharedKeyCredential doesn't need a specific test method because other tests below * use connection string, which is converted to a ServiceBusSharedKeyCredential internally. */ @ParameterizedTest @MethodSource("createHttpClients") @ParameterizedTest @MethodSource("createHttpClients") void createQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueExistingName(HttpClient httpClient) { final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions options = new CreateQueueOptions(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createQueue(queueName, options)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final String forwardToEntityName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions expected = new CreateQueueOptions() .setForwardTo(forwardToEntityName) .setForwardDeadLetteredMessagesTo(forwardToEntityName); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueAuthorizationRules(HttpClient httpClient) { final String keyName = "test-rule"; final List<AccessRights> accessRights = Collections.singletonList(AccessRights.SEND); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final SharedAccessAuthorizationRule rule = interceptorManager.isPlaybackMode() ? new SharedAccessAuthorizationRule(keyName, "REDACTED", "REDACTED", accessRights) : new SharedAccessAuthorizationRule(keyName, accessRights); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); expected.getAuthorizationRules().add(rule); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); assertAuthorizationRules(expected.getAuthorizationRules(), actual.getAuthorizationRules()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction action = new SqlRuleAction("SET Label = 'test'"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(action) .setFilter(new FalseRuleFilter()); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName, options)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(action.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof FalseRuleFilter); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleDefaults(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName)) .assertNext(contents -> { assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleFilter filter = new SqlRuleFilter("sys.To=@MyParameter OR sys.MessageId IS NULL"); filter.getParameters().put("@MyParameter", "My-Parameter-Value"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(new EmptyRuleAction()) .setFilter(filter); StepVerifier.create(client.createRuleWithResponse(topicName, subscriptionName, ruleName, options)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); final SqlRuleFilter actualFilter = (SqlRuleFilter) contents.getFilter(); assertEquals(filter.getSqlExpression(), actualFilter.getSqlExpression()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 0); final String subscriptionName = testResourceNamer.randomName("sub", 10); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setUserMetadata("some-metadata-for-testing-subscriptions"); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionExistingName(HttpClient httpClient) { final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createSubscription(topicName, subscriptionName)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 3); final String subscriptionName = testResourceNamer.randomName("sub", 50); final String forwardToTopic = getEntityName(getTopicBaseName(), 4); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setForwardTo(forwardToTopic) .setForwardDeadLetteredMessagesTo(forwardToTopic); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } }) .expectComplete() .verify(TIMEOUT); } @ParameterizedTest @MethodSource("createHttpClients") void createTopicWithResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("test", 10); final CreateTopicOptions expected = new CreateTopicOptions() .setMaxSizeInMegabytes(2048L) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing-topic"); StepVerifier.create(client.createTopicWithResponse(topicName, expected)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final TopicProperties actual = response.getValue(); assertEquals(topicName, actual.getName()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(actual); assertEquals(0, runtimeProperties.getSubscriptionCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("sub", 10); client.createQueue(queueName) .onErrorResume(ResourceExistsException.class, e -> Mono.empty()) .block(TIMEOUT); StepVerifier.create(client.deleteQueue(queueName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule-", 11); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); StepVerifier.create(client.deleteRule(topicName, subscriptionName, ruleName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); final String subscriptionName = testResourceNamer.randomName("sub", 7); client.createTopic(topicName).block(TIMEOUT); client.createSubscription(topicName, subscriptionName).block(TIMEOUT); StepVerifier.create(client.deleteSubscription(topicName, subscriptionName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); client.createTopic(topicName).block(TIMEOUT); StepVerifier.create(client.deleteTopic(topicName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueue(queueName)) .assertNext(queueDescription -> { assertEquals(queueName, queueDescription.getName()); assertFalse(queueDescription.isPartitioningEnabled()); assertFalse(queueDescription.isSessionRequired()); assertNotNull(queueDescription.getLockDuration()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(queueDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getNamespace(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertEquals(NamespaceType.MESSAGING, properties.getNamespaceType()); assertEquals(expectedName, properties.getName()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueue(queueName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueueRuntimeProperties(queueName)) .assertNext(RuntimeProperties -> { assertEquals(queueName, RuntimeProperties.getName()); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.getRuleWithResponse(topicName, subscriptionName, ruleName)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.isSessionRequired()); assertNotNull(description.getLockDuration()); final SubscriptionRuntimeProperties runtimeProperties = new SubscriptionRuntimeProperties(description); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.getTotalMessageCount() >= 0); assertEquals(0, description.getActiveMessageCount()); assertEquals(0, description.getTransferDeadLetterMessageCount()); assertEquals(0, description.getTransferMessageCount()); assertTrue(description.getDeadLetterMessageCount() >= 0); assertNotNull(description.getCreatedAt()); assertTrue(nowUtc.isAfter(description.getCreatedAt())); assertNotNull(description.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopic(topicName)) .assertNext(topicDescription -> { assertEquals(topicName, topicDescription.getName()); assertTrue(topicDescription.isBatchedOperationsEnabled()); assertFalse(topicDescription.isDuplicateDetectionRequired()); assertNotNull(topicDescription.getDuplicateDetectionHistoryTimeWindow()); assertNotNull(topicDescription.getDefaultMessageTimeToLive()); assertFalse(topicDescription.isPartitioningEnabled()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(topicDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopic(topicName)) .consumeErrorWith(error -> { assertTrue(error instanceof ResourceNotFoundException); final ResourceNotFoundException notFoundError = (ResourceNotFoundException) error; final HttpResponse response = notFoundError.getResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); StepVerifier.create(response.getBody()) .verifyComplete(); }) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopicRuntimeProperties(topicName)) .assertNext(RuntimeProperties -> { assertEquals(topicName, RuntimeProperties.getName()); assertTrue(RuntimeProperties.getSubscriptionCount() > 1); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getAccessedAt())); assertEquals(0, RuntimeProperties.getScheduledMessageCount()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimePropertiesUnauthorizedClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final String connectionStringUpdated = connectionString.replace("SharedAccessKey=", "SharedAccessKey=fake-key-"); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionStringUpdated); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } final ServiceBusAdministrationAsyncClient client = builder.buildAsyncClient(); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getEntityName(getSubscriptionBaseName(), 2); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .verifyErrorMatches(throwable -> throwable instanceof ClientAuthenticationException); } @ParameterizedTest @MethodSource("createHttpClients") void listRules(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.listRules(topicName, subscriptionName)) .assertNext(response -> { assertEquals(ruleName, response.getName()); assertNotNull(response.getFilter()); assertTrue(response.getFilter() instanceof TrueRuleFilter); assertNotNull(response.getAction()); assertTrue(response.getAction() instanceof EmptyRuleAction); }) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listQueues(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listQueues()) .assertNext(queueDescription -> { assertNotNull(queueDescription.getName()); assertTrue(queueDescription.isBatchedOperationsEnabled()); assertFalse(queueDescription.isDuplicateDetectionRequired()); assertFalse(queueDescription.isPartitioningEnabled()); }) .expectNextCount(9) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listSubscriptions(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.listSubscriptions(topicName)) .assertNext(subscription -> { assertEquals(topicName, subscription.getTopicName()); assertNotNull(subscription.getSubscriptionName()); }) .expectNextCount(1) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listTopics(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listTopics()) .assertNext(topics -> { assertNotNull(topics.getName()); assertTrue(topics.isBatchedOperationsEnabled()); assertFalse(topics.isPartitioningEnabled()); }) .expectNextCount(2) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void updateRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 15); final String topicName = getEntityName(getTopicBaseName(), 12); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction expectedAction = new SqlRuleAction("SET MessageId = 'matching-id'"); final SqlRuleFilter expectedFilter = new SqlRuleFilter("sys.To = 'telemetry-event'"); final RuleProperties existingRule = client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); assertNotNull(existingRule); existingRule.setAction(expectedAction).setFilter(expectedFilter); StepVerifier.create(client.updateRule(topicName, subscriptionName, existingRule)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); assertEquals(expectedFilter.getSqlExpression(), ((SqlRuleFilter) contents.getFilter()).getSqlExpression()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(expectedAction.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); }) .verifyComplete(); } private ServiceBusAdministrationAsyncClient createClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionString); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } return builder.buildAsyncClient(); } }
Not sure. It was there before for our HTTP client tests. I can remove it.
void azureIdentityCredentials(HttpClient httpClient) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(); final TokenCredential tokenCredential = getTokenCredential(); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder(); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient) .addPolicy(new RetryPolicy()); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } final ServiceBusAdministrationAsyncClient client = builder .credential(fullyQualifiedDomainName, tokenCredential) .buildAsyncClient(); StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertNotNull(properties); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } assertEquals(expectedName, properties.getName()); }) .verifyComplete(); }
.addPolicy(new RetryPolicy());
void azureIdentityCredentials(HttpClient httpClient) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(); final TokenCredential tokenCredential; if (interceptorManager.isPlaybackMode()) { tokenCredential = mock(TokenCredential.class); Mockito.when(tokenCredential.getToken(any(TokenRequestContext.class))).thenReturn(Mono.fromCallable(() -> { return new AccessToken("foo-bar", OffsetDateTime.now().plus(Duration.ofMinutes(5))); })); } else { tokenCredential = new DefaultAzureCredentialBuilder().build(); } final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder(); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } final ServiceBusAdministrationAsyncClient client = builder .credential(fullyQualifiedDomainName, tokenCredential) .buildAsyncClient(); StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertNotNull(properties); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } assertEquals(expectedName, properties.getName()); }) .verifyComplete(); }
class ServiceBusAdministrationAsyncClientIntegrationTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(20); @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(10)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } static Stream<Arguments> createHttpClients() { return Stream.of( Arguments.of(new NettyAsyncHttpClientBuilder().build()) ); } /** * Test to connect to the service bus with an azure identity TokenCredential. * com.azure.identity.ClientSecretCredential is used in this test. * ServiceBusSharedKeyCredential doesn't need a specific test method because other tests below * use connection string, which is converted to a ServiceBusSharedKeyCredential internally. */ @ParameterizedTest @MethodSource("createHttpClients") @ParameterizedTest @MethodSource("createHttpClients") void createQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueExistingName(HttpClient httpClient) { final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions options = new CreateQueueOptions(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createQueue(queueName, options)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final String forwardToEntityName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions expected = new CreateQueueOptions() .setForwardTo(forwardToEntityName) .setForwardDeadLetteredMessagesTo(forwardToEntityName); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueAuthorizationRules(HttpClient httpClient) { final String keyName = "test-rule"; final List<AccessRights> accessRights = Collections.singletonList(AccessRights.SEND); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final SharedAccessAuthorizationRule rule = interceptorManager.isPlaybackMode() ? new SharedAccessAuthorizationRule(keyName, "REDACTED", "REDACTED", accessRights) : new SharedAccessAuthorizationRule(keyName, accessRights); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); expected.getAuthorizationRules().add(rule); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); assertAuthorizationRules(expected.getAuthorizationRules(), actual.getAuthorizationRules()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction action = new SqlRuleAction("SET Label = 'test'"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(action) .setFilter(new FalseRuleFilter()); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName, options)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(action.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof FalseRuleFilter); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleDefaults(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName)) .assertNext(contents -> { assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleFilter filter = new SqlRuleFilter("sys.To=@MyParameter OR sys.MessageId IS NULL"); filter.getParameters().put("@MyParameter", "My-Parameter-Value"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(new EmptyRuleAction()) .setFilter(filter); StepVerifier.create(client.createRuleWithResponse(topicName, subscriptionName, ruleName, options)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); final SqlRuleFilter actualFilter = (SqlRuleFilter) contents.getFilter(); assertEquals(filter.getSqlExpression(), actualFilter.getSqlExpression()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 0); final String subscriptionName = testResourceNamer.randomName("sub", 10); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setUserMetadata("some-metadata-for-testing-subscriptions"); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionExistingName(HttpClient httpClient) { final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createSubscription(topicName, subscriptionName)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 3); final String subscriptionName = testResourceNamer.randomName("sub", 50); final String forwardToTopic = getEntityName(getTopicBaseName(), 4); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setForwardTo(forwardToTopic) .setForwardDeadLetteredMessagesTo(forwardToTopic); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } }) .expectComplete() .verify(TIMEOUT); } @ParameterizedTest @MethodSource("createHttpClients") void createTopicWithResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("test", 10); final CreateTopicOptions expected = new CreateTopicOptions() .setMaxSizeInMegabytes(2048L) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing-topic"); StepVerifier.create(client.createTopicWithResponse(topicName, expected)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final TopicProperties actual = response.getValue(); assertEquals(topicName, actual.getName()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(actual); assertEquals(0, runtimeProperties.getSubscriptionCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("sub", 10); client.createQueue(queueName) .onErrorResume(ResourceExistsException.class, e -> Mono.empty()) .block(TIMEOUT); StepVerifier.create(client.deleteQueue(queueName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule-", 11); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); StepVerifier.create(client.deleteRule(topicName, subscriptionName, ruleName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); final String subscriptionName = testResourceNamer.randomName("sub", 7); client.createTopic(topicName).block(TIMEOUT); client.createSubscription(topicName, subscriptionName).block(TIMEOUT); StepVerifier.create(client.deleteSubscription(topicName, subscriptionName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); client.createTopic(topicName).block(TIMEOUT); StepVerifier.create(client.deleteTopic(topicName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueue(queueName)) .assertNext(queueDescription -> { assertEquals(queueName, queueDescription.getName()); assertFalse(queueDescription.isPartitioningEnabled()); assertFalse(queueDescription.isSessionRequired()); assertNotNull(queueDescription.getLockDuration()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(queueDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getNamespace(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertEquals(NamespaceType.MESSAGING, properties.getNamespaceType()); assertEquals(expectedName, properties.getName()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueue(queueName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueueRuntimeProperties(queueName)) .assertNext(RuntimeProperties -> { assertEquals(queueName, RuntimeProperties.getName()); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.getRuleWithResponse(topicName, subscriptionName, ruleName)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.isSessionRequired()); assertNotNull(description.getLockDuration()); final SubscriptionRuntimeProperties runtimeProperties = new SubscriptionRuntimeProperties(description); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.getTotalMessageCount() >= 0); assertEquals(0, description.getActiveMessageCount()); assertEquals(0, description.getTransferDeadLetterMessageCount()); assertEquals(0, description.getTransferMessageCount()); assertTrue(description.getDeadLetterMessageCount() >= 0); assertNotNull(description.getCreatedAt()); assertTrue(nowUtc.isAfter(description.getCreatedAt())); assertNotNull(description.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopic(topicName)) .assertNext(topicDescription -> { assertEquals(topicName, topicDescription.getName()); assertTrue(topicDescription.isBatchedOperationsEnabled()); assertFalse(topicDescription.isDuplicateDetectionRequired()); assertNotNull(topicDescription.getDuplicateDetectionHistoryTimeWindow()); assertNotNull(topicDescription.getDefaultMessageTimeToLive()); assertFalse(topicDescription.isPartitioningEnabled()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(topicDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopic(topicName)) .consumeErrorWith(error -> { assertTrue(error instanceof ResourceNotFoundException); final ResourceNotFoundException notFoundError = (ResourceNotFoundException) error; final HttpResponse response = notFoundError.getResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); StepVerifier.create(response.getBody()) .verifyComplete(); }) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopicRuntimeProperties(topicName)) .assertNext(RuntimeProperties -> { assertEquals(topicName, RuntimeProperties.getName()); assertTrue(RuntimeProperties.getSubscriptionCount() > 1); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getAccessedAt())); assertEquals(0, RuntimeProperties.getScheduledMessageCount()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimePropertiesUnauthorizedClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final String connectionStringUpdated = connectionString.replace("SharedAccessKey=", "SharedAccessKey=fake-key-"); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionStringUpdated); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient) .addPolicy(new RetryPolicy()); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } final ServiceBusAdministrationAsyncClient client = builder.buildAsyncClient(); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getEntityName(getSubscriptionBaseName(), 2); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .verifyErrorMatches(throwable -> throwable instanceof ClientAuthenticationException); } @ParameterizedTest @MethodSource("createHttpClients") void listRules(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.listRules(topicName, subscriptionName)) .assertNext(response -> { assertEquals(ruleName, response.getName()); assertNotNull(response.getFilter()); assertTrue(response.getFilter() instanceof TrueRuleFilter); assertNotNull(response.getAction()); assertTrue(response.getAction() instanceof EmptyRuleAction); }) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listQueues(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listQueues()) .assertNext(queueDescription -> { assertNotNull(queueDescription.getName()); assertTrue(queueDescription.isBatchedOperationsEnabled()); assertFalse(queueDescription.isDuplicateDetectionRequired()); assertFalse(queueDescription.isPartitioningEnabled()); }) .expectNextCount(9) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listSubscriptions(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.listSubscriptions(topicName)) .assertNext(subscription -> { assertEquals(topicName, subscription.getTopicName()); assertNotNull(subscription.getSubscriptionName()); }) .expectNextCount(1) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listTopics(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listTopics()) .assertNext(topics -> { assertNotNull(topics.getName()); assertTrue(topics.isBatchedOperationsEnabled()); assertFalse(topics.isPartitioningEnabled()); }) .expectNextCount(2) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void updateRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 15); final String topicName = getEntityName(getTopicBaseName(), 12); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction expectedAction = new SqlRuleAction("SET MessageId = 'matching-id'"); final SqlRuleFilter expectedFilter = new SqlRuleFilter("sys.To = 'telemetry-event'"); final RuleProperties existingRule = client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); assertNotNull(existingRule); existingRule.setAction(expectedAction).setFilter(expectedFilter); StepVerifier.create(client.updateRule(topicName, subscriptionName, existingRule)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); assertEquals(expectedFilter.getSqlExpression(), ((SqlRuleFilter) contents.getFilter()).getSqlExpression()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(expectedAction.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); }) .verifyComplete(); } private ServiceBusAdministrationAsyncClient createClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionString); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient) .addPolicy(new RetryPolicy()); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } return builder.buildAsyncClient(); } private TokenCredential getTokenCredential() { final DefaultAzureCredentialBuilder builder = new DefaultAzureCredentialBuilder(); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } return builder.build(); } }
class ServiceBusAdministrationAsyncClientIntegrationTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(20); @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(10)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } static Stream<Arguments> createHttpClients() { return Stream.of( Arguments.of(new NettyAsyncHttpClientBuilder().build()) ); } /** * Test to connect to the service bus with an azure identity TokenCredential. * com.azure.identity.ClientSecretCredential is used in this test. * ServiceBusSharedKeyCredential doesn't need a specific test method because other tests below * use connection string, which is converted to a ServiceBusSharedKeyCredential internally. */ @ParameterizedTest @MethodSource("createHttpClients") @ParameterizedTest @MethodSource("createHttpClients") void createQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueExistingName(HttpClient httpClient) { final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions options = new CreateQueueOptions(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createQueue(queueName, options)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final String forwardToEntityName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions expected = new CreateQueueOptions() .setForwardTo(forwardToEntityName) .setForwardDeadLetteredMessagesTo(forwardToEntityName); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueAuthorizationRules(HttpClient httpClient) { final String keyName = "test-rule"; final List<AccessRights> accessRights = Collections.singletonList(AccessRights.SEND); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final SharedAccessAuthorizationRule rule = interceptorManager.isPlaybackMode() ? new SharedAccessAuthorizationRule(keyName, "REDACTED", "REDACTED", accessRights) : new SharedAccessAuthorizationRule(keyName, accessRights); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); expected.getAuthorizationRules().add(rule); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); assertAuthorizationRules(expected.getAuthorizationRules(), actual.getAuthorizationRules()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction action = new SqlRuleAction("SET Label = 'test'"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(action) .setFilter(new FalseRuleFilter()); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName, options)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(action.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof FalseRuleFilter); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleDefaults(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName)) .assertNext(contents -> { assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleFilter filter = new SqlRuleFilter("sys.To=@MyParameter OR sys.MessageId IS NULL"); filter.getParameters().put("@MyParameter", "My-Parameter-Value"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(new EmptyRuleAction()) .setFilter(filter); StepVerifier.create(client.createRuleWithResponse(topicName, subscriptionName, ruleName, options)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); final SqlRuleFilter actualFilter = (SqlRuleFilter) contents.getFilter(); assertEquals(filter.getSqlExpression(), actualFilter.getSqlExpression()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 0); final String subscriptionName = testResourceNamer.randomName("sub", 10); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setUserMetadata("some-metadata-for-testing-subscriptions"); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionExistingName(HttpClient httpClient) { final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createSubscription(topicName, subscriptionName)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 3); final String subscriptionName = testResourceNamer.randomName("sub", 50); final String forwardToTopic = getEntityName(getTopicBaseName(), 4); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setForwardTo(forwardToTopic) .setForwardDeadLetteredMessagesTo(forwardToTopic); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } }) .expectComplete() .verify(TIMEOUT); } @ParameterizedTest @MethodSource("createHttpClients") void createTopicWithResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("test", 10); final CreateTopicOptions expected = new CreateTopicOptions() .setMaxSizeInMegabytes(2048L) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing-topic"); StepVerifier.create(client.createTopicWithResponse(topicName, expected)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final TopicProperties actual = response.getValue(); assertEquals(topicName, actual.getName()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(actual); assertEquals(0, runtimeProperties.getSubscriptionCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("sub", 10); client.createQueue(queueName) .onErrorResume(ResourceExistsException.class, e -> Mono.empty()) .block(TIMEOUT); StepVerifier.create(client.deleteQueue(queueName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule-", 11); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); StepVerifier.create(client.deleteRule(topicName, subscriptionName, ruleName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); final String subscriptionName = testResourceNamer.randomName("sub", 7); client.createTopic(topicName).block(TIMEOUT); client.createSubscription(topicName, subscriptionName).block(TIMEOUT); StepVerifier.create(client.deleteSubscription(topicName, subscriptionName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); client.createTopic(topicName).block(TIMEOUT); StepVerifier.create(client.deleteTopic(topicName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueue(queueName)) .assertNext(queueDescription -> { assertEquals(queueName, queueDescription.getName()); assertFalse(queueDescription.isPartitioningEnabled()); assertFalse(queueDescription.isSessionRequired()); assertNotNull(queueDescription.getLockDuration()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(queueDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getNamespace(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertEquals(NamespaceType.MESSAGING, properties.getNamespaceType()); assertEquals(expectedName, properties.getName()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueue(queueName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueueRuntimeProperties(queueName)) .assertNext(RuntimeProperties -> { assertEquals(queueName, RuntimeProperties.getName()); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.getRuleWithResponse(topicName, subscriptionName, ruleName)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.isSessionRequired()); assertNotNull(description.getLockDuration()); final SubscriptionRuntimeProperties runtimeProperties = new SubscriptionRuntimeProperties(description); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.getTotalMessageCount() >= 0); assertEquals(0, description.getActiveMessageCount()); assertEquals(0, description.getTransferDeadLetterMessageCount()); assertEquals(0, description.getTransferMessageCount()); assertTrue(description.getDeadLetterMessageCount() >= 0); assertNotNull(description.getCreatedAt()); assertTrue(nowUtc.isAfter(description.getCreatedAt())); assertNotNull(description.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopic(topicName)) .assertNext(topicDescription -> { assertEquals(topicName, topicDescription.getName()); assertTrue(topicDescription.isBatchedOperationsEnabled()); assertFalse(topicDescription.isDuplicateDetectionRequired()); assertNotNull(topicDescription.getDuplicateDetectionHistoryTimeWindow()); assertNotNull(topicDescription.getDefaultMessageTimeToLive()); assertFalse(topicDescription.isPartitioningEnabled()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(topicDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopic(topicName)) .consumeErrorWith(error -> { assertTrue(error instanceof ResourceNotFoundException); final ResourceNotFoundException notFoundError = (ResourceNotFoundException) error; final HttpResponse response = notFoundError.getResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); StepVerifier.create(response.getBody()) .verifyComplete(); }) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopicRuntimeProperties(topicName)) .assertNext(RuntimeProperties -> { assertEquals(topicName, RuntimeProperties.getName()); assertTrue(RuntimeProperties.getSubscriptionCount() > 1); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getAccessedAt())); assertEquals(0, RuntimeProperties.getScheduledMessageCount()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimePropertiesUnauthorizedClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final String connectionStringUpdated = connectionString.replace("SharedAccessKey=", "SharedAccessKey=fake-key-"); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionStringUpdated); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } final ServiceBusAdministrationAsyncClient client = builder.buildAsyncClient(); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getEntityName(getSubscriptionBaseName(), 2); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .verifyErrorMatches(throwable -> throwable instanceof ClientAuthenticationException); } @ParameterizedTest @MethodSource("createHttpClients") void listRules(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.listRules(topicName, subscriptionName)) .assertNext(response -> { assertEquals(ruleName, response.getName()); assertNotNull(response.getFilter()); assertTrue(response.getFilter() instanceof TrueRuleFilter); assertNotNull(response.getAction()); assertTrue(response.getAction() instanceof EmptyRuleAction); }) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listQueues(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listQueues()) .assertNext(queueDescription -> { assertNotNull(queueDescription.getName()); assertTrue(queueDescription.isBatchedOperationsEnabled()); assertFalse(queueDescription.isDuplicateDetectionRequired()); assertFalse(queueDescription.isPartitioningEnabled()); }) .expectNextCount(9) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listSubscriptions(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.listSubscriptions(topicName)) .assertNext(subscription -> { assertEquals(topicName, subscription.getTopicName()); assertNotNull(subscription.getSubscriptionName()); }) .expectNextCount(1) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listTopics(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listTopics()) .assertNext(topics -> { assertNotNull(topics.getName()); assertTrue(topics.isBatchedOperationsEnabled()); assertFalse(topics.isPartitioningEnabled()); }) .expectNextCount(2) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void updateRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 15); final String topicName = getEntityName(getTopicBaseName(), 12); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction expectedAction = new SqlRuleAction("SET MessageId = 'matching-id'"); final SqlRuleFilter expectedFilter = new SqlRuleFilter("sys.To = 'telemetry-event'"); final RuleProperties existingRule = client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); assertNotNull(existingRule); existingRule.setAction(expectedAction).setFilter(expectedFilter); StepVerifier.create(client.updateRule(topicName, subscriptionName, existingRule)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); assertEquals(expectedFilter.getSqlExpression(), ((SqlRuleFilter) contents.getFilter()).getSqlExpression()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(expectedAction.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); }) .verifyComplete(); } private ServiceBusAdministrationAsyncClient createClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionString); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } return builder.buildAsyncClient(); } }
Matchers only need to be added in playback mode. As the "Match" only when playing it back.
private ServiceBusAdministrationAsyncClient createClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionString); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } interceptorManager.addSanitizers(TEST_PROXY_SANITIZERS); interceptorManager.addMatchers(TEST_PROXY_REQUEST_MATCHERS); return builder.buildAsyncClient(); }
interceptorManager.addMatchers(TEST_PROXY_REQUEST_MATCHERS);
private ServiceBusAdministrationAsyncClient createClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionString); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers(TEST_PROXY_SANITIZERS); interceptorManager.addMatchers(TEST_PROXY_REQUEST_MATCHERS); } return builder.buildAsyncClient(); }
class ServiceBusAdministrationAsyncClientIntegrationTest extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(20); /** * Sanitizer to remove header values for ServiceBusDlqSupplementaryAuthorization and * ServiceBusSupplementaryAuthorization. */ static final TestProxySanitizer AUTHORIZATION_HEADER; static final List<TestProxySanitizer> TEST_PROXY_SANITIZERS; static final List<TestProxyRequestMatcher> TEST_PROXY_REQUEST_MATCHERS; static { AUTHORIZATION_HEADER = new TestProxySanitizer("SupplementaryAuthorization", "SharedAccessSignature sr=https%3A%2F%2Ffoo.servicebus.windows.net&sig=dummyValue%3D&se=1687267490&skn=dummyKey", TestProxySanitizerType.HEADER); TEST_PROXY_SANITIZERS = Collections.singletonList(AUTHORIZATION_HEADER); final List<String> skippedHeaders = Arrays.asList("ServiceBusDlqSupplementaryAuthorization", "ServiceBusSupplementaryAuthorization"); final CustomMatcher customMatcher = new CustomMatcher().setExcludedHeaders(skippedHeaders); TEST_PROXY_REQUEST_MATCHERS = Collections.singletonList(customMatcher); } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(10)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } static Stream<Arguments> createHttpClients() { return Stream.of( Arguments.of(new NettyAsyncHttpClientBuilder().build()) ); } /** * Test to connect to the service bus with an azure identity TokenCredential. * com.azure.identity.ClientSecretCredential is used in this test. * ServiceBusSharedKeyCredential doesn't need a specific test method because other tests below * use connection string, which is converted to a ServiceBusSharedKeyCredential internally. */ @ParameterizedTest @MethodSource("createHttpClients") void azureIdentityCredentials(HttpClient httpClient) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(); final TokenCredential tokenCredential; if (interceptorManager.isPlaybackMode()) { tokenCredential = mock(TokenCredential.class); Mockito.when(tokenCredential.getToken(any(TokenRequestContext.class))).thenReturn(Mono.fromCallable(() -> { return new AccessToken("foo-bar", OffsetDateTime.now().plus(Duration.ofMinutes(5))); })); } else { tokenCredential = new DefaultAzureCredentialBuilder().build(); } final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder(); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } final ServiceBusAdministrationAsyncClient client = builder .credential(fullyQualifiedDomainName, tokenCredential) .buildAsyncClient(); StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertNotNull(properties); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } assertEquals(expectedName, properties.getName()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueExistingName(HttpClient httpClient) { final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions options = new CreateQueueOptions(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createQueue(queueName, options)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final String forwardToEntityName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions expected = new CreateQueueOptions() .setForwardTo(forwardToEntityName) .setForwardDeadLetteredMessagesTo(forwardToEntityName); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueAuthorizationRules(HttpClient httpClient) { final String keyName = "test-rule"; final List<AccessRights> accessRights = Collections.singletonList(AccessRights.SEND); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final SharedAccessAuthorizationRule rule = interceptorManager.isPlaybackMode() ? new SharedAccessAuthorizationRule(keyName, "REDACTED", "REDACTED", accessRights) : new SharedAccessAuthorizationRule(keyName, accessRights); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); expected.getAuthorizationRules().add(rule); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); assertAuthorizationRules(expected.getAuthorizationRules(), actual.getAuthorizationRules()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction action = new SqlRuleAction("SET Label = 'test'"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(action) .setFilter(new FalseRuleFilter()); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName, options)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(action.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof FalseRuleFilter); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleDefaults(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName)) .assertNext(contents -> { assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleFilter filter = new SqlRuleFilter("sys.To=@MyParameter OR sys.MessageId IS NULL"); filter.getParameters().put("@MyParameter", "My-Parameter-Value"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(new EmptyRuleAction()) .setFilter(filter); StepVerifier.create(client.createRuleWithResponse(topicName, subscriptionName, ruleName, options)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); final SqlRuleFilter actualFilter = (SqlRuleFilter) contents.getFilter(); assertEquals(filter.getSqlExpression(), actualFilter.getSqlExpression()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 0); final String subscriptionName = testResourceNamer.randomName("sub", 10); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setUserMetadata("some-metadata-for-testing-subscriptions"); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionExistingName(HttpClient httpClient) { final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createSubscription(topicName, subscriptionName)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 3); final String subscriptionName = testResourceNamer.randomName("sub", 50); final String forwardToTopic = getEntityName(getTopicBaseName(), 4); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setForwardTo(forwardToTopic) .setForwardDeadLetteredMessagesTo(forwardToTopic); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } }) .expectComplete() .verify(TIMEOUT); } @ParameterizedTest @MethodSource("createHttpClients") void createTopicWithResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("test", 10); final CreateTopicOptions expected = new CreateTopicOptions() .setMaxSizeInMegabytes(2048L) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing-topic"); StepVerifier.create(client.createTopicWithResponse(topicName, expected)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final TopicProperties actual = response.getValue(); assertEquals(topicName, actual.getName()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(actual); assertEquals(0, runtimeProperties.getSubscriptionCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("sub", 10); client.createQueue(queueName) .onErrorResume(ResourceExistsException.class, e -> Mono.empty()) .block(TIMEOUT); StepVerifier.create(client.deleteQueue(queueName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule-", 11); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); StepVerifier.create(client.deleteRule(topicName, subscriptionName, ruleName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); final String subscriptionName = testResourceNamer.randomName("sub", 7); client.createTopic(topicName).block(TIMEOUT); client.createSubscription(topicName, subscriptionName).block(TIMEOUT); StepVerifier.create(client.deleteSubscription(topicName, subscriptionName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); client.createTopic(topicName).block(TIMEOUT); StepVerifier.create(client.deleteTopic(topicName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueue(queueName)) .assertNext(queueDescription -> { assertEquals(queueName, queueDescription.getName()); assertFalse(queueDescription.isPartitioningEnabled()); assertFalse(queueDescription.isSessionRequired()); assertNotNull(queueDescription.getLockDuration()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(queueDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getNamespace(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertEquals(NamespaceType.MESSAGING, properties.getNamespaceType()); assertEquals(expectedName, properties.getName()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueue(queueName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueueRuntimeProperties(queueName)) .assertNext(RuntimeProperties -> { assertEquals(queueName, RuntimeProperties.getName()); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.getRuleWithResponse(topicName, subscriptionName, ruleName)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.isSessionRequired()); assertNotNull(description.getLockDuration()); final SubscriptionRuntimeProperties runtimeProperties = new SubscriptionRuntimeProperties(description); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.getTotalMessageCount() >= 0); assertEquals(0, description.getActiveMessageCount()); assertEquals(0, description.getTransferDeadLetterMessageCount()); assertEquals(0, description.getTransferMessageCount()); assertTrue(description.getDeadLetterMessageCount() >= 0); assertNotNull(description.getCreatedAt()); assertTrue(nowUtc.isAfter(description.getCreatedAt())); assertNotNull(description.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopic(topicName)) .assertNext(topicDescription -> { assertEquals(topicName, topicDescription.getName()); assertTrue(topicDescription.isBatchedOperationsEnabled()); assertFalse(topicDescription.isDuplicateDetectionRequired()); assertNotNull(topicDescription.getDuplicateDetectionHistoryTimeWindow()); assertNotNull(topicDescription.getDefaultMessageTimeToLive()); assertFalse(topicDescription.isPartitioningEnabled()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(topicDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopic(topicName)) .consumeErrorWith(error -> { assertTrue(error instanceof ResourceNotFoundException); final ResourceNotFoundException notFoundError = (ResourceNotFoundException) error; final HttpResponse response = notFoundError.getResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); StepVerifier.create(response.getBody()) .verifyComplete(); }) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopicRuntimeProperties(topicName)) .assertNext(RuntimeProperties -> { assertEquals(topicName, RuntimeProperties.getName()); assertTrue(RuntimeProperties.getSubscriptionCount() > 1); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getAccessedAt())); assertEquals(0, RuntimeProperties.getScheduledMessageCount()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimePropertiesUnauthorizedClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final String connectionStringUpdated = connectionString.replace("SharedAccessKey=", "SharedAccessKey=fake-key-"); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionStringUpdated); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } final ServiceBusAdministrationAsyncClient client = builder.buildAsyncClient(); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getEntityName(getSubscriptionBaseName(), 2); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .verifyErrorMatches(throwable -> throwable instanceof ClientAuthenticationException); } @ParameterizedTest @MethodSource("createHttpClients") void listRules(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.listRules(topicName, subscriptionName)) .assertNext(response -> { assertEquals(ruleName, response.getName()); assertNotNull(response.getFilter()); assertTrue(response.getFilter() instanceof TrueRuleFilter); assertNotNull(response.getAction()); assertTrue(response.getAction() instanceof EmptyRuleAction); }) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listQueues(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listQueues()) .assertNext(queueDescription -> { assertNotNull(queueDescription.getName()); assertTrue(queueDescription.isBatchedOperationsEnabled()); assertFalse(queueDescription.isDuplicateDetectionRequired()); assertFalse(queueDescription.isPartitioningEnabled()); }) .expectNextCount(9) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listSubscriptions(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.listSubscriptions(topicName)) .assertNext(subscription -> { assertEquals(topicName, subscription.getTopicName()); assertNotNull(subscription.getSubscriptionName()); }) .expectNextCount(1) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listTopics(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listTopics()) .assertNext(topics -> { assertNotNull(topics.getName()); assertTrue(topics.isBatchedOperationsEnabled()); assertFalse(topics.isPartitioningEnabled()); }) .expectNextCount(2) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void updateRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 15); final String topicName = getEntityName(getTopicBaseName(), 12); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction expectedAction = new SqlRuleAction("SET MessageId = 'matching-id'"); final SqlRuleFilter expectedFilter = new SqlRuleFilter("sys.To = 'telemetry-event'"); final RuleProperties existingRule = client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); assertNotNull(existingRule); existingRule.setAction(expectedAction).setFilter(expectedFilter); StepVerifier.create(client.updateRule(topicName, subscriptionName, existingRule)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); assertEquals(expectedFilter.getSqlExpression(), ((SqlRuleFilter) contents.getFilter()).getSqlExpression()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(expectedAction.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); }) .verifyComplete(); } }
class ServiceBusAdministrationAsyncClientIntegrationTest extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(20); /** * Sanitizer to remove header values for ServiceBusDlqSupplementaryAuthorization and * ServiceBusSupplementaryAuthorization. */ static final TestProxySanitizer AUTHORIZATION_HEADER; static final List<TestProxySanitizer> TEST_PROXY_SANITIZERS; static final List<TestProxyRequestMatcher> TEST_PROXY_REQUEST_MATCHERS; static { AUTHORIZATION_HEADER = new TestProxySanitizer("SupplementaryAuthorization", "SharedAccessSignature sr=https%3A%2F%2Ffoo.servicebus.windows.net&sig=dummyValue%3D&se=1687267490&skn=dummyKey", TestProxySanitizerType.HEADER); TEST_PROXY_SANITIZERS = Collections.singletonList(AUTHORIZATION_HEADER); final List<String> skippedHeaders = Arrays.asList("ServiceBusDlqSupplementaryAuthorization", "ServiceBusSupplementaryAuthorization"); final CustomMatcher customMatcher = new CustomMatcher().setExcludedHeaders(skippedHeaders); TEST_PROXY_REQUEST_MATCHERS = Collections.singletonList(customMatcher); } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(10)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } static Stream<Arguments> createHttpClients() { return Stream.of( Arguments.of(new NettyAsyncHttpClientBuilder().build()) ); } /** * Test to connect to the service bus with an azure identity TokenCredential. * com.azure.identity.ClientSecretCredential is used in this test. * ServiceBusSharedKeyCredential doesn't need a specific test method because other tests below * use connection string, which is converted to a ServiceBusSharedKeyCredential internally. */ @ParameterizedTest @MethodSource("createHttpClients") void azureIdentityCredentials(HttpClient httpClient) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(); final TokenCredential tokenCredential; if (interceptorManager.isPlaybackMode()) { tokenCredential = mock(TokenCredential.class); Mockito.when(tokenCredential.getToken(any(TokenRequestContext.class))).thenReturn(Mono.fromCallable(() -> { return new AccessToken("foo-bar", OffsetDateTime.now().plus(Duration.ofMinutes(5))); })); } else { tokenCredential = new DefaultAzureCredentialBuilder().build(); } final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder(); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } final ServiceBusAdministrationAsyncClient client = builder .credential(fullyQualifiedDomainName, tokenCredential) .buildAsyncClient(); StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertNotNull(properties); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } assertEquals(expectedName, properties.getName()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueExistingName(HttpClient httpClient) { final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions options = new CreateQueueOptions(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createQueue(queueName, options)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final String forwardToEntityName = getEntityName(TestUtils.getQueueBaseName(), 5); final CreateQueueOptions expected = new CreateQueueOptions() .setForwardTo(forwardToEntityName) .setForwardDeadLetteredMessagesTo(forwardToEntityName); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createQueueAuthorizationRules(HttpClient httpClient) { final String keyName = "test-rule"; final List<AccessRights> accessRights = Collections.singletonList(AccessRights.SEND); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("test", 10); final SharedAccessAuthorizationRule rule = interceptorManager.isPlaybackMode() ? new SharedAccessAuthorizationRule(keyName, "REDACTED", "REDACTED", accessRights) : new SharedAccessAuthorizationRule(keyName, accessRights); final CreateQueueOptions expected = new CreateQueueOptions() .setMaxSizeInMegabytes(1024) .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setSessionRequired(true) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing"); expected.getAuthorizationRules().add(rule); StepVerifier.create(client.createQueue(queueName, expected)) .assertNext(actual -> { assertEquals(queueName, actual.getName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual); assertEquals(0, runtimeProperties.getTotalMessageCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); assertAuthorizationRules(expected.getAuthorizationRules(), actual.getAuthorizationRules()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction action = new SqlRuleAction("SET Label = 'test'"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(action) .setFilter(new FalseRuleFilter()); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName, options)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(action.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof FalseRuleFilter); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleDefaults(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.createRule(topicName, subscriptionName, ruleName)) .assertNext(contents -> { assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 10); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleFilter filter = new SqlRuleFilter("sys.To=@MyParameter OR sys.MessageId IS NULL"); filter.getParameters().put("@MyParameter", "My-Parameter-Value"); final CreateRuleOptions options = new CreateRuleOptions() .setAction(new EmptyRuleAction()) .setFilter(filter); StepVerifier.create(client.createRuleWithResponse(topicName, subscriptionName, ruleName, options)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); final SqlRuleFilter actualFilter = (SqlRuleFilter) contents.getFilter(); assertEquals(filter.getSqlExpression(), actualFilter.getSqlExpression()); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 0); final String subscriptionName = testResourceNamer.randomName("sub", 10); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setMaxDeliveryCount(7) .setLockDuration(Duration.ofSeconds(45)) .setUserMetadata("some-metadata-for-testing-subscriptions"); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.isSessionRequired(), actual.isSessionRequired()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionExistingName(HttpClient httpClient) { final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.createSubscription(topicName, subscriptionName)) .expectError(ResourceExistsException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void createSubscriptionWithForwarding(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 3); final String subscriptionName = testResourceNamer.randomName("sub", 50); final String forwardToTopic = getEntityName(getTopicBaseName(), 4); final CreateSubscriptionOptions expected = new CreateSubscriptionOptions() .setForwardTo(forwardToTopic) .setForwardDeadLetteredMessagesTo(forwardToTopic); StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected)) .assertNext(actual -> { assertEquals(topicName, actual.getTopicName()); assertEquals(subscriptionName, actual.getSubscriptionName()); if (!interceptorManager.isPlaybackMode()) { assertEquals(expected.getForwardTo(), actual.getForwardTo()); assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo()); } }) .expectComplete() .verify(TIMEOUT); } @ParameterizedTest @MethodSource("createHttpClients") void createTopicWithResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("test", 10); final CreateTopicOptions expected = new CreateTopicOptions() .setMaxSizeInMegabytes(2048L) .setDuplicateDetectionRequired(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2)) .setUserMetadata("some-metadata-for-testing-topic"); StepVerifier.create(client.createTopicWithResponse(topicName, expected)) .assertNext(response -> { assertEquals(201, response.getStatusCode()); final TopicProperties actual = response.getValue(); assertEquals(topicName, actual.getName()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); assertEquals(expected.isPartitioningEnabled(), actual.isPartitioningEnabled()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isDuplicateDetectionRequired()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(actual); assertEquals(0, runtimeProperties.getSubscriptionCount()); assertEquals(0, runtimeProperties.getSizeInBytes()); assertNotNull(runtimeProperties.getCreatedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("sub", 10); client.createQueue(queueName) .onErrorResume(ResourceExistsException.class, e -> Mono.empty()) .block(TIMEOUT); StepVerifier.create(client.deleteQueue(queueName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule-", 11); final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); StepVerifier.create(client.deleteRule(topicName, subscriptionName, ruleName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); final String subscriptionName = testResourceNamer.randomName("sub", 7); client.createTopic(topicName).block(TIMEOUT); client.createSubscription(topicName, subscriptionName).block(TIMEOUT); StepVerifier.create(client.deleteSubscription(topicName, subscriptionName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void deleteTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("topic", 10); client.createTopic(topicName).block(TIMEOUT); StepVerifier.create(client.deleteTopic(topicName)) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueue(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 5); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueue(queueName)) .assertNext(queueDescription -> { assertEquals(queueName, queueDescription.getName()); assertFalse(queueDescription.isPartitioningEnabled()); assertFalse(queueDescription.isSessionRequired()); assertNotNull(queueDescription.getLockDuration()); final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(queueDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getNamespace(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String expectedName; if (interceptorManager.isPlaybackMode()) { expectedName = TestUtils.TEST_NAMESPACE; } else { final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2); expectedName = split[0]; } StepVerifier.create(client.getNamespaceProperties()) .assertNext(properties -> { assertEquals(NamespaceType.MESSAGING, properties.getNamespaceType()); assertEquals(expectedName, properties.getName()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueue(queueName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = testResourceNamer.randomName("exist", 10); StepVerifier.create(client.getQueueExists(queueName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getQueueRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String queueName = getEntityName(TestUtils.getQueueBaseName(), 2); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getQueueRuntimeProperties(queueName)) .assertNext(RuntimeProperties -> { assertEquals(queueName, RuntimeProperties.getName()); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getRule(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.getRuleWithResponse(topicName, subscriptionName, ruleName)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); final RuleProperties contents = response.getValue(); assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertNotNull(contents.getFilter()); assertTrue(contents.getFilter() instanceof TrueRuleFilter); assertNotNull(contents.getAction()); assertTrue(contents.getAction() instanceof EmptyRuleAction); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscription(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.isSessionRequired()); assertNotNull(description.getLockDuration()); final SubscriptionRuntimeProperties runtimeProperties = new SubscriptionRuntimeProperties(description); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscription(topicName, subscriptionName)) .expectError(ResourceNotFoundException.class) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = "subscription-session-not-exist"; StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getSessionSubscriptionBaseName(); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .assertNext(description -> { assertEquals(topicName, description.getTopicName()); assertEquals(subscriptionName, description.getSubscriptionName()); assertTrue(description.getTotalMessageCount() >= 0); assertEquals(0, description.getActiveMessageCount()); assertEquals(0, description.getTransferDeadLetterMessageCount()); assertEquals(0, description.getTransferMessageCount()); assertTrue(description.getDeadLetterMessageCount() >= 0); assertNotNull(description.getCreatedAt()); assertTrue(nowUtc.isAfter(description.getCreatedAt())); assertNotNull(description.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopic(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopic(topicName)) .assertNext(topicDescription -> { assertEquals(topicName, topicDescription.getName()); assertTrue(topicDescription.isBatchedOperationsEnabled()); assertFalse(topicDescription.isDuplicateDetectionRequired()); assertNotNull(topicDescription.getDuplicateDetectionHistoryTimeWindow()); assertNotNull(topicDescription.getDefaultMessageTimeToLive()); assertFalse(topicDescription.isPartitioningEnabled()); final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(topicDescription); assertNotNull(runtimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt())); assertNotNull(runtimeProperties.getAccessedAt()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicDoesNotExist(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopic(topicName)) .consumeErrorWith(error -> { assertTrue(error instanceof ResourceNotFoundException); final ResourceNotFoundException notFoundError = (ResourceNotFoundException) error; final HttpResponse response = notFoundError.getResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); StepVerifier.create(response.getBody()) .verifyComplete(); }) .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExists(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(true) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicExistsFalse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = testResourceNamer.randomName("exists", 10); StepVerifier.create(client.getTopicExists(topicName)) .expectNext(false) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getTopicRuntimeProperties(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC()); StepVerifier.create(client.getTopicRuntimeProperties(topicName)) .assertNext(RuntimeProperties -> { assertEquals(topicName, RuntimeProperties.getName()); assertTrue(RuntimeProperties.getSubscriptionCount() > 1); assertNotNull(RuntimeProperties.getCreatedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt())); assertNotNull(RuntimeProperties.getAccessedAt()); assertTrue(nowUtc.isAfter(RuntimeProperties.getAccessedAt())); assertEquals(0, RuntimeProperties.getScheduledMessageCount()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("createHttpClients") void getSubscriptionRuntimePropertiesUnauthorizedClient(HttpClient httpClient) { final String connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=sb: : TestUtils.getConnectionString(false); final String connectionStringUpdated = connectionString.replace("SharedAccessKey=", "SharedAccessKey=fake-key-"); final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .connectionString(connectionStringUpdated); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isLiveMode()) { builder.httpClient(httpClient); } else { builder.httpClient(httpClient) .addPolicy(interceptorManager.getRecordPolicy()); } final ServiceBusAdministrationAsyncClient client = builder.buildAsyncClient(); final String topicName = getEntityName(getTopicBaseName(), 1); final String subscriptionName = getEntityName(getSubscriptionBaseName(), 2); StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName)) .verifyErrorMatches(throwable -> throwable instanceof ClientAuthenticationException); } @ParameterizedTest @MethodSource("createHttpClients") void listRules(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = "$Default"; final String topicName = getEntityName(getTopicBaseName(), 13); final String subscriptionName = getSubscriptionBaseName(); StepVerifier.create(client.listRules(topicName, subscriptionName)) .assertNext(response -> { assertEquals(ruleName, response.getName()); assertNotNull(response.getFilter()); assertTrue(response.getFilter() instanceof TrueRuleFilter); assertNotNull(response.getAction()); assertTrue(response.getAction() instanceof EmptyRuleAction); }) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listQueues(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listQueues()) .assertNext(queueDescription -> { assertNotNull(queueDescription.getName()); assertTrue(queueDescription.isBatchedOperationsEnabled()); assertFalse(queueDescription.isDuplicateDetectionRequired()); assertFalse(queueDescription.isPartitioningEnabled()); }) .expectNextCount(9) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listSubscriptions(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String topicName = getEntityName(getTopicBaseName(), 1); StepVerifier.create(client.listSubscriptions(topicName)) .assertNext(subscription -> { assertEquals(topicName, subscription.getTopicName()); assertNotNull(subscription.getSubscriptionName()); }) .expectNextCount(1) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void listTopics(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); StepVerifier.create(client.listTopics()) .assertNext(topics -> { assertNotNull(topics.getName()); assertTrue(topics.isBatchedOperationsEnabled()); assertFalse(topics.isPartitioningEnabled()); }) .expectNextCount(2) .thenCancel() .verify(); } @ParameterizedTest @MethodSource("createHttpClients") void updateRuleResponse(HttpClient httpClient) { final ServiceBusAdministrationAsyncClient client = createClient(httpClient); final String ruleName = testResourceNamer.randomName("rule", 15); final String topicName = getEntityName(getTopicBaseName(), 12); final String subscriptionName = getSubscriptionBaseName(); final SqlRuleAction expectedAction = new SqlRuleAction("SET MessageId = 'matching-id'"); final SqlRuleFilter expectedFilter = new SqlRuleFilter("sys.To = 'telemetry-event'"); final RuleProperties existingRule = client.createRule(topicName, subscriptionName, ruleName).block(TIMEOUT); assertNotNull(existingRule); existingRule.setAction(expectedAction).setFilter(expectedFilter); StepVerifier.create(client.updateRule(topicName, subscriptionName, existingRule)) .assertNext(contents -> { assertNotNull(contents); assertEquals(ruleName, contents.getName()); assertTrue(contents.getFilter() instanceof SqlRuleFilter); assertEquals(expectedFilter.getSqlExpression(), ((SqlRuleFilter) contents.getFilter()).getSqlExpression()); assertTrue(contents.getAction() instanceof SqlRuleAction); assertEquals(expectedAction.getSqlExpression(), ((SqlRuleAction) contents.getAction()).getSqlExpression()); }) .verifyComplete(); } }
I thought in Spring, there is `ResponseDiagnosticsProcessor`. would there cause any overlap with the `diagnosticsHandler` ?
public CosmosClientBuilder secondaryCosmosClientBuilder() { return new CosmosClientBuilder() .key(cosmosDbKey) .endpoint(cosmosDbUri) .contentResponseOnWriteEnabled(true) .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setNonPointOperationLatencyThreshold(Duration.ofSeconds(nonPointOperationLatencyThreshold)) .setPointOperationLatencyThreshold(Duration.ofSeconds(pointOperationLatencyThreshold)) .setPayloadSizeThreshold(payloadSizeInBytesThreshold) .setRequestChargeThreshold(requestChargeThreshold) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER)); }
.clientTelemetryConfig(
public CosmosClientBuilder secondaryCosmosClientBuilder() { return new CosmosClientBuilder() .key(cosmosDbKey) .endpoint(cosmosDbUri) .contentResponseOnWriteEnabled(true) .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setNonPointOperationLatencyThreshold(Duration.ofMillis(nonPointOperationLatencyThresholdInMS)) .setPointOperationLatencyThreshold(Duration.ofMillis(pointOperationLatencyThresholdInMS)) .setPayloadSizeThreshold(payloadSizeThresholdInBytes) .setRequestChargeThreshold(requestChargeThresholdInRU) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER)); }
class SecondaryTestRepositoryConfig { @Value("${cosmos.secondary.uri:}") private String cosmosDbUri; @Value("${cosmos.secondary.key:}") private String cosmosDbKey; @Value("${cosmos.secondary.database:}") private String database; @Value("${cosmos.secondary.queryMetricsEnabled}") private boolean queryMetricsEnabled; @Value("${cosmos.secondary.maxDegreeOfParallelism}") private int maxDegreeOfParallelism; @Value("${cosmos.secondary.maxBufferedItemCount}") private int maxBufferedItemCount; @Value("${cosmos.secondary.responseContinuationTokenLimitInKb}") private int responseContinuationTokenLimitInKb; @Value("${cosmos.diagnosticsThresholds.pointOperationLatencyThreshold}") private int pointOperationLatencyThreshold; @Value("${cosmos.diagnosticsThresholds.nonPointOperationLatencyThreshold}") private int nonPointOperationLatencyThreshold; @Value("${cosmos.diagnosticsThresholds.requestChargeThreshold}") private int requestChargeThreshold; @Value("${cosmos.diagnosticsThresholds.payloadSizeInBytesThreshold}") private int payloadSizeInBytesThreshold; @Bean @Bean("secondaryCosmosAsyncClient") public CosmosAsyncClient getCosmosAsyncClient(CosmosClientBuilder secondaryCosmosClientBuilder) { return CosmosFactory.createCosmosAsyncClient(secondaryCosmosClientBuilder); } /** * First database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate") public class SecondaryDataSourceConfiguration { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getFirstDatabase()), config, mappingCosmosConverter); } } /** * Second database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate1") public class SecondaryDataSourceConfiguration1 { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate1(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getSecondDatabase()), config, mappingCosmosConverter); } } private String getFirstDatabase() { return StringUtils.hasText(this.database) ? this.database : "test_db_1"; } private String getSecondDatabase() { return "test_db_2"; } }
class SecondaryTestRepositoryConfig { @Value("${cosmos.secondary.uri:}") private String cosmosDbUri; @Value("${cosmos.secondary.key:}") private String cosmosDbKey; @Value("${cosmos.secondary.database:}") private String database; @Value("${cosmos.secondary.queryMetricsEnabled}") private boolean queryMetricsEnabled; @Value("${cosmos.secondary.maxDegreeOfParallelism}") private int maxDegreeOfParallelism; @Value("${cosmos.secondary.maxBufferedItemCount}") private int maxBufferedItemCount; @Value("${cosmos.secondary.responseContinuationTokenLimitInKb}") private int responseContinuationTokenLimitInKb; @Value("${cosmos.diagnosticsThresholds.pointOperationLatencyThresholdInMS}") private int pointOperationLatencyThresholdInMS; @Value("${cosmos.diagnosticsThresholds.nonPointOperationLatencyThresholdInMS}") private int nonPointOperationLatencyThresholdInMS; @Value("${cosmos.diagnosticsThresholds.requestChargeThresholdInRU}") private int requestChargeThresholdInRU; @Value("${cosmos.diagnosticsThresholds.payloadSizeThresholdInBytes}") private int payloadSizeThresholdInBytes; @Bean @Bean("secondaryCosmosAsyncClient") public CosmosAsyncClient getCosmosAsyncClient(CosmosClientBuilder secondaryCosmosClientBuilder) { return CosmosFactory.createCosmosAsyncClient(secondaryCosmosClientBuilder); } /** * First database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate") public class SecondaryDataSourceConfiguration { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getFirstDatabase()), config, mappingCosmosConverter); } } /** * Second database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate1") public class SecondaryDataSourceConfiguration1 { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate1(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getSecondDatabase()), config, mappingCosmosConverter); } } private String getFirstDatabase() { return StringUtils.hasText(this.database) ? this.database : "test_db_1"; } private String getSecondDatabase() { return "test_db_2"; } }
I don't think there is any overlap, `ResponseDiagnosticsProcesor` is used to process the response from a query where as `diagnosticsHandler` is on the `CosmosClientBuilder`. Any thoughts @kushagraThapar ?
public CosmosClientBuilder secondaryCosmosClientBuilder() { return new CosmosClientBuilder() .key(cosmosDbKey) .endpoint(cosmosDbUri) .contentResponseOnWriteEnabled(true) .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setNonPointOperationLatencyThreshold(Duration.ofSeconds(nonPointOperationLatencyThreshold)) .setPointOperationLatencyThreshold(Duration.ofSeconds(pointOperationLatencyThreshold)) .setPayloadSizeThreshold(payloadSizeInBytesThreshold) .setRequestChargeThreshold(requestChargeThreshold) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER)); }
.clientTelemetryConfig(
public CosmosClientBuilder secondaryCosmosClientBuilder() { return new CosmosClientBuilder() .key(cosmosDbKey) .endpoint(cosmosDbUri) .contentResponseOnWriteEnabled(true) .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setNonPointOperationLatencyThreshold(Duration.ofMillis(nonPointOperationLatencyThresholdInMS)) .setPointOperationLatencyThreshold(Duration.ofMillis(pointOperationLatencyThresholdInMS)) .setPayloadSizeThreshold(payloadSizeThresholdInBytes) .setRequestChargeThreshold(requestChargeThresholdInRU) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER)); }
class SecondaryTestRepositoryConfig { @Value("${cosmos.secondary.uri:}") private String cosmosDbUri; @Value("${cosmos.secondary.key:}") private String cosmosDbKey; @Value("${cosmos.secondary.database:}") private String database; @Value("${cosmos.secondary.queryMetricsEnabled}") private boolean queryMetricsEnabled; @Value("${cosmos.secondary.maxDegreeOfParallelism}") private int maxDegreeOfParallelism; @Value("${cosmos.secondary.maxBufferedItemCount}") private int maxBufferedItemCount; @Value("${cosmos.secondary.responseContinuationTokenLimitInKb}") private int responseContinuationTokenLimitInKb; @Value("${cosmos.diagnosticsThresholds.pointOperationLatencyThreshold}") private int pointOperationLatencyThreshold; @Value("${cosmos.diagnosticsThresholds.nonPointOperationLatencyThreshold}") private int nonPointOperationLatencyThreshold; @Value("${cosmos.diagnosticsThresholds.requestChargeThreshold}") private int requestChargeThreshold; @Value("${cosmos.diagnosticsThresholds.payloadSizeInBytesThreshold}") private int payloadSizeInBytesThreshold; @Bean @Bean("secondaryCosmosAsyncClient") public CosmosAsyncClient getCosmosAsyncClient(CosmosClientBuilder secondaryCosmosClientBuilder) { return CosmosFactory.createCosmosAsyncClient(secondaryCosmosClientBuilder); } /** * First database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate") public class SecondaryDataSourceConfiguration { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getFirstDatabase()), config, mappingCosmosConverter); } } /** * Second database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate1") public class SecondaryDataSourceConfiguration1 { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate1(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getSecondDatabase()), config, mappingCosmosConverter); } } private String getFirstDatabase() { return StringUtils.hasText(this.database) ? this.database : "test_db_1"; } private String getSecondDatabase() { return "test_db_2"; } }
class SecondaryTestRepositoryConfig { @Value("${cosmos.secondary.uri:}") private String cosmosDbUri; @Value("${cosmos.secondary.key:}") private String cosmosDbKey; @Value("${cosmos.secondary.database:}") private String database; @Value("${cosmos.secondary.queryMetricsEnabled}") private boolean queryMetricsEnabled; @Value("${cosmos.secondary.maxDegreeOfParallelism}") private int maxDegreeOfParallelism; @Value("${cosmos.secondary.maxBufferedItemCount}") private int maxBufferedItemCount; @Value("${cosmos.secondary.responseContinuationTokenLimitInKb}") private int responseContinuationTokenLimitInKb; @Value("${cosmos.diagnosticsThresholds.pointOperationLatencyThresholdInMS}") private int pointOperationLatencyThresholdInMS; @Value("${cosmos.diagnosticsThresholds.nonPointOperationLatencyThresholdInMS}") private int nonPointOperationLatencyThresholdInMS; @Value("${cosmos.diagnosticsThresholds.requestChargeThresholdInRU}") private int requestChargeThresholdInRU; @Value("${cosmos.diagnosticsThresholds.payloadSizeThresholdInBytes}") private int payloadSizeThresholdInBytes; @Bean @Bean("secondaryCosmosAsyncClient") public CosmosAsyncClient getCosmosAsyncClient(CosmosClientBuilder secondaryCosmosClientBuilder) { return CosmosFactory.createCosmosAsyncClient(secondaryCosmosClientBuilder); } /** * First database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate") public class SecondaryDataSourceConfiguration { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getFirstDatabase()), config, mappingCosmosConverter); } } /** * Second database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate1") public class SecondaryDataSourceConfiguration1 { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate1(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getSecondDatabase()), config, mappingCosmosConverter); } } private String getFirstDatabase() { return StringUtils.hasText(this.database) ? this.database : "test_db_1"; } private String getSecondDatabase() { return "test_db_2"; } }
Actually, `ResponseDiagnosticsProcessor` is used for all operations in spring-data-cosmos. So it might overlap, we should let customers know to use `DiagnosticsHandler` on `CosmosClientBuilder` going forward. @trande4884 - we should add more samples / documentation on this in the readme section, and samples section.
public CosmosClientBuilder secondaryCosmosClientBuilder() { return new CosmosClientBuilder() .key(cosmosDbKey) .endpoint(cosmosDbUri) .contentResponseOnWriteEnabled(true) .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setNonPointOperationLatencyThreshold(Duration.ofSeconds(nonPointOperationLatencyThreshold)) .setPointOperationLatencyThreshold(Duration.ofSeconds(pointOperationLatencyThreshold)) .setPayloadSizeThreshold(payloadSizeInBytesThreshold) .setRequestChargeThreshold(requestChargeThreshold) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER)); }
.clientTelemetryConfig(
public CosmosClientBuilder secondaryCosmosClientBuilder() { return new CosmosClientBuilder() .key(cosmosDbKey) .endpoint(cosmosDbUri) .contentResponseOnWriteEnabled(true) .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setNonPointOperationLatencyThreshold(Duration.ofMillis(nonPointOperationLatencyThresholdInMS)) .setPointOperationLatencyThreshold(Duration.ofMillis(pointOperationLatencyThresholdInMS)) .setPayloadSizeThreshold(payloadSizeThresholdInBytes) .setRequestChargeThreshold(requestChargeThresholdInRU) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER)); }
class SecondaryTestRepositoryConfig { @Value("${cosmos.secondary.uri:}") private String cosmosDbUri; @Value("${cosmos.secondary.key:}") private String cosmosDbKey; @Value("${cosmos.secondary.database:}") private String database; @Value("${cosmos.secondary.queryMetricsEnabled}") private boolean queryMetricsEnabled; @Value("${cosmos.secondary.maxDegreeOfParallelism}") private int maxDegreeOfParallelism; @Value("${cosmos.secondary.maxBufferedItemCount}") private int maxBufferedItemCount; @Value("${cosmos.secondary.responseContinuationTokenLimitInKb}") private int responseContinuationTokenLimitInKb; @Value("${cosmos.diagnosticsThresholds.pointOperationLatencyThreshold}") private int pointOperationLatencyThreshold; @Value("${cosmos.diagnosticsThresholds.nonPointOperationLatencyThreshold}") private int nonPointOperationLatencyThreshold; @Value("${cosmos.diagnosticsThresholds.requestChargeThreshold}") private int requestChargeThreshold; @Value("${cosmos.diagnosticsThresholds.payloadSizeInBytesThreshold}") private int payloadSizeInBytesThreshold; @Bean @Bean("secondaryCosmosAsyncClient") public CosmosAsyncClient getCosmosAsyncClient(CosmosClientBuilder secondaryCosmosClientBuilder) { return CosmosFactory.createCosmosAsyncClient(secondaryCosmosClientBuilder); } /** * First database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate") public class SecondaryDataSourceConfiguration { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getFirstDatabase()), config, mappingCosmosConverter); } } /** * Second database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate1") public class SecondaryDataSourceConfiguration1 { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate1(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getSecondDatabase()), config, mappingCosmosConverter); } } private String getFirstDatabase() { return StringUtils.hasText(this.database) ? this.database : "test_db_1"; } private String getSecondDatabase() { return "test_db_2"; } }
class SecondaryTestRepositoryConfig { @Value("${cosmos.secondary.uri:}") private String cosmosDbUri; @Value("${cosmos.secondary.key:}") private String cosmosDbKey; @Value("${cosmos.secondary.database:}") private String database; @Value("${cosmos.secondary.queryMetricsEnabled}") private boolean queryMetricsEnabled; @Value("${cosmos.secondary.maxDegreeOfParallelism}") private int maxDegreeOfParallelism; @Value("${cosmos.secondary.maxBufferedItemCount}") private int maxBufferedItemCount; @Value("${cosmos.secondary.responseContinuationTokenLimitInKb}") private int responseContinuationTokenLimitInKb; @Value("${cosmos.diagnosticsThresholds.pointOperationLatencyThresholdInMS}") private int pointOperationLatencyThresholdInMS; @Value("${cosmos.diagnosticsThresholds.nonPointOperationLatencyThresholdInMS}") private int nonPointOperationLatencyThresholdInMS; @Value("${cosmos.diagnosticsThresholds.requestChargeThresholdInRU}") private int requestChargeThresholdInRU; @Value("${cosmos.diagnosticsThresholds.payloadSizeThresholdInBytes}") private int payloadSizeThresholdInBytes; @Bean @Bean("secondaryCosmosAsyncClient") public CosmosAsyncClient getCosmosAsyncClient(CosmosClientBuilder secondaryCosmosClientBuilder) { return CosmosFactory.createCosmosAsyncClient(secondaryCosmosClientBuilder); } /** * First database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate") public class SecondaryDataSourceConfiguration { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getFirstDatabase()), config, mappingCosmosConverter); } } /** * Second database for this account */ @EnableReactiveCosmosRepositories(reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate1") public class SecondaryDataSourceConfiguration1 { @Bean public ReactiveCosmosTemplate secondaryReactiveCosmosTemplate1(@Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client, MappingCosmosConverter mappingCosmosConverter) { CosmosConfig config = CosmosConfig.builder() .enableQueryMetrics(queryMetricsEnabled) .maxDegreeOfParallelism(maxDegreeOfParallelism) .maxBufferedItemCount(maxBufferedItemCount) .responseContinuationTokenLimitInKb(responseContinuationTokenLimitInKb) .build(); return new ReactiveCosmosTemplate(new CosmosFactory(client, getSecondDatabase()), config, mappingCosmosConverter); } } private String getFirstDatabase() { return StringUtils.hasText(this.database) ? this.database : "test_db_1"; } private String getSecondDatabase() { return "test_db_2"; } }
There may be some problem here on parsing the name. The `@PathParam("name") String name` in RestProxy is not encoded. Here `encodeResourceId(diagnosticSettingId)` may get the name encoded (along with resourceUri). Hence the name may get encoded twice (once here, once in RestProxy).
private String getNameFromSettingsId(String diagnosticSettingId) { String resourceId = getResourceIdFromSettingsId(diagnosticSettingId); return ResourceUtils.encodeResourceId(diagnosticSettingId) .substring(resourceId.length() + DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI.length()); }
}
private String getNameFromSettingsId(String diagnosticSettingId) { String resourceId = getResourceIdFromSettingsId(diagnosticSettingId, false); return diagnosticSettingId .substring(resourceId.length() + DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI.length()); }
class DiagnosticSettingsImpl extends CreatableResourcesImpl<DiagnosticSetting, DiagnosticSettingImpl, DiagnosticSettingsResourceInner> implements DiagnosticSettings { private final ClientLogger logger = new ClientLogger(getClass()); private final MonitorManager manager; public DiagnosticSettingsImpl(final MonitorManager manager) { this.manager = manager; } @Override public DiagnosticSettingImpl define(String name) { return wrapModel(name); } @Override protected DiagnosticSettingImpl wrapModel(String name) { DiagnosticSettingsResourceInner inner = new DiagnosticSettingsResourceInner(); return new DiagnosticSettingImpl(name, inner, this.manager()); } @Override protected DiagnosticSettingImpl wrapModel(DiagnosticSettingsResourceInner inner) { if (inner == null) { return null; } return new DiagnosticSettingImpl(inner.name(), inner, this.manager()); } @Override public MonitorManager manager() { return this.manager; } public DiagnosticSettingsOperationsClient inner() { return this.manager().serviceClient().getDiagnosticSettingsOperations(); } @Override public List<DiagnosticSettingsCategory> listCategoriesByResource(String resourceId) { List<DiagnosticSettingsCategory> categories = new ArrayList<>(); PagedIterable<DiagnosticSettingsCategoryResourceInner> collection = this.manager().serviceClient().getDiagnosticSettingsCategories().list(ResourceUtils.encodeResourceId(resourceId)); if (collection != null) { for (DiagnosticSettingsCategoryResourceInner category : collection) { categories.add(new DiagnosticSettingsCategoryImpl(category)); } } return categories; } @Override public PagedFlux<DiagnosticSettingsCategory> listCategoriesByResourceAsync(String resourceId) { return PagedConverter.mapPage(this .manager .serviceClient() .getDiagnosticSettingsCategories() .listAsync(ResourceUtils.encodeResourceId(resourceId)), DiagnosticSettingsCategoryImpl::new); } @Override public DiagnosticSettingsCategory getCategory(String resourceId, String name) { return new DiagnosticSettingsCategoryImpl( this.manager().serviceClient().getDiagnosticSettingsCategories().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSettingsCategory> getCategoryAsync(String resourceId, String name) { return this .manager() .serviceClient() .getDiagnosticSettingsCategories() .getAsync(ResourceUtils.encodeResourceId(resourceId), name) .map(DiagnosticSettingsCategoryImpl::new); } @Override public PagedIterable<DiagnosticSetting> listByResource(String resourceId) { return new PagedIterable<>(this.listByResourceAsync(resourceId)); } @Override public PagedFlux<DiagnosticSetting> listByResourceAsync(String resourceId) { return PagedConverter.mapPage( this .manager() .serviceClient() .getDiagnosticSettingsOperations() .listAsync(ResourceUtils.encodeResourceId(resourceId)), inner -> new DiagnosticSettingImpl(inner.name(), inner, manager)); } @Override public void delete(String resourceId, String name) { this.manager().serviceClient().getDiagnosticSettingsOperations().delete(ResourceUtils.encodeResourceId(resourceId), name); } @Override public Mono<Void> deleteAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().deleteAsync(ResourceUtils.encodeResourceId(resourceId), name); } @Override public DiagnosticSetting get(String resourceId, String name) { return wrapModel(this.manager().serviceClient().getDiagnosticSettingsOperations().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSetting> getAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(ResourceUtils.encodeResourceId(resourceId), name).map(this::wrapModel); } @Override public Mono<Void> deleteByIdAsync(String id) { return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)); } @Override public Flux<String> deleteByIdsAsync(Collection<String> ids) { if (CoreUtils.isNullOrEmpty(ids)) { return Flux.empty(); } return Flux.fromIterable(ids) .flatMapDelayError(id -> deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).then(Mono.just(id)), 32, 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); } @Override public Flux<String> deleteByIdsAsync(String... ids) { return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids))); } @Override public void deleteByIds(Collection<String> ids) { if (ids != null && !ids.isEmpty()) { this.deleteByIdsAsync(ids).blockLast(); } } @Override public void deleteByIds(String... ids) { this.deleteByIds(new ArrayList<>(Arrays.asList(ids))); } @Override public DiagnosticSetting getById(String id) { return wrapModel(this.inner().get(getResourceIdFromSettingsId(id), getNameFromSettingsId(id))); } @Override public Mono<DiagnosticSetting> getByIdAsync(String id) { return this.inner().getAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).map(this::wrapModel); } private String getResourceIdFromSettingsId(String diagnosticSettingId) { diagnosticSettingId = ResourceUtils.encodeResourceId(diagnosticSettingId); if (diagnosticSettingId == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Parameter 'resourceId' is required and cannot be null.")); } int dsIdx = diagnosticSettingId.lastIndexOf(DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI); if (dsIdx == -1) { throw logger.logExceptionAsError(new IllegalArgumentException( "Parameter 'resourceId' does not represent a valid Diagnostic Settings resource Id [" + diagnosticSettingId + "].")); } return diagnosticSettingId.substring(0, dsIdx); } }
class DiagnosticSettingsImpl extends CreatableResourcesImpl<DiagnosticSetting, DiagnosticSettingImpl, DiagnosticSettingsResourceInner> implements DiagnosticSettings { private final ClientLogger logger = new ClientLogger(getClass()); private final MonitorManager manager; public DiagnosticSettingsImpl(final MonitorManager manager) { this.manager = manager; } @Override public DiagnosticSettingImpl define(String name) { return wrapModel(name); } @Override protected DiagnosticSettingImpl wrapModel(String name) { DiagnosticSettingsResourceInner inner = new DiagnosticSettingsResourceInner(); return new DiagnosticSettingImpl(name, inner, this.manager()); } @Override protected DiagnosticSettingImpl wrapModel(DiagnosticSettingsResourceInner inner) { if (inner == null) { return null; } return new DiagnosticSettingImpl(inner.name(), inner, this.manager()); } @Override public MonitorManager manager() { return this.manager; } public DiagnosticSettingsOperationsClient inner() { return this.manager().serviceClient().getDiagnosticSettingsOperations(); } @Override public List<DiagnosticSettingsCategory> listCategoriesByResource(String resourceId) { List<DiagnosticSettingsCategory> categories = new ArrayList<>(); PagedIterable<DiagnosticSettingsCategoryResourceInner> collection = this.manager().serviceClient().getDiagnosticSettingsCategories().list(ResourceUtils.encodeResourceId(resourceId)); if (collection != null) { for (DiagnosticSettingsCategoryResourceInner category : collection) { categories.add(new DiagnosticSettingsCategoryImpl(category)); } } return categories; } @Override public PagedFlux<DiagnosticSettingsCategory> listCategoriesByResourceAsync(String resourceId) { return PagedConverter.mapPage(this .manager .serviceClient() .getDiagnosticSettingsCategories() .listAsync(ResourceUtils.encodeResourceId(resourceId)), DiagnosticSettingsCategoryImpl::new); } @Override public DiagnosticSettingsCategory getCategory(String resourceId, String name) { return new DiagnosticSettingsCategoryImpl( this.manager().serviceClient().getDiagnosticSettingsCategories().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSettingsCategory> getCategoryAsync(String resourceId, String name) { return this .manager() .serviceClient() .getDiagnosticSettingsCategories() .getAsync(ResourceUtils.encodeResourceId(resourceId), name) .map(DiagnosticSettingsCategoryImpl::new); } @Override public PagedIterable<DiagnosticSetting> listByResource(String resourceId) { return new PagedIterable<>(this.listByResourceAsync(resourceId)); } @Override public PagedFlux<DiagnosticSetting> listByResourceAsync(String resourceId) { return PagedConverter.mapPage( this .manager() .serviceClient() .getDiagnosticSettingsOperations() .listAsync(ResourceUtils.encodeResourceId(resourceId)), inner -> new DiagnosticSettingImpl(inner.name(), inner, manager)); } @Override public void delete(String resourceId, String name) { this.manager().serviceClient().getDiagnosticSettingsOperations().delete(ResourceUtils.encodeResourceId(resourceId), name); } @Override public Mono<Void> deleteAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().deleteAsync(ResourceUtils.encodeResourceId(resourceId), name); } @Override public DiagnosticSetting get(String resourceId, String name) { return wrapModel(this.manager().serviceClient().getDiagnosticSettingsOperations().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSetting> getAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(ResourceUtils.encodeResourceId(resourceId), name).map(this::wrapModel); } @Override public Mono<Void> deleteByIdAsync(String id) { return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)); } @Override public Flux<String> deleteByIdsAsync(Collection<String> ids) { if (CoreUtils.isNullOrEmpty(ids)) { return Flux.empty(); } return Flux.fromIterable(ids) .flatMapDelayError(id -> deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).then(Mono.just(id)), 32, 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); } @Override public Flux<String> deleteByIdsAsync(String... ids) { return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids))); } @Override public void deleteByIds(Collection<String> ids) { if (ids != null && !ids.isEmpty()) { this.deleteByIdsAsync(ids).blockLast(); } } @Override public void deleteByIds(String... ids) { this.deleteByIds(new ArrayList<>(Arrays.asList(ids))); } @Override public DiagnosticSetting getById(String id) { return wrapModel(this.inner().get(getResourceIdFromSettingsId(id), getNameFromSettingsId(id))); } @Override public Mono<DiagnosticSetting> getByIdAsync(String id) { return this.inner().getAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).map(this::wrapModel); } /** * Get the resourceID from the diagnostic setting ID, with proper encoding. * * @param diagnosticSettingId ID of the diagnostic setting resource * @return properly encoded resourceID of the diagnostic setting */ private String getResourceIdFromSettingsId(String diagnosticSettingId) { return getResourceIdFromSettingsId(diagnosticSettingId, true); } /** * Get the resourceID from the diagnostic setting ID. * * @param diagnosticSettingId ID of the diagnostic setting resource * @param encodeResourceId whether to ensure the resourceID is properly encoded * @return resourceID of the diagnostic setting */ private String getResourceIdFromSettingsId(String diagnosticSettingId, boolean encodeResourceId) { if (diagnosticSettingId == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Parameter 'resourceId' is required and cannot be null.")); } if (encodeResourceId) { diagnosticSettingId = ResourceUtils.encodeResourceId(diagnosticSettingId); } int dsIdx = diagnosticSettingId.lastIndexOf(DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI); if (dsIdx == -1) { throw logger.logExceptionAsError(new IllegalArgumentException( "Parameter 'resourceId' does not represent a valid Diagnostic Settings resource Id [" + diagnosticSettingId + "].")); } return diagnosticSettingId.substring(0, dsIdx); } /** * Get raw diagnostic setting name from id. * * @param diagnosticSettingId ID of the diagnostic settting * @return raw name of the diagnostic setting */ }
Got it. name shouldn't be encoded, thanks!
private String getNameFromSettingsId(String diagnosticSettingId) { String resourceId = getResourceIdFromSettingsId(diagnosticSettingId); return ResourceUtils.encodeResourceId(diagnosticSettingId) .substring(resourceId.length() + DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI.length()); }
}
private String getNameFromSettingsId(String diagnosticSettingId) { String resourceId = getResourceIdFromSettingsId(diagnosticSettingId, false); return diagnosticSettingId .substring(resourceId.length() + DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI.length()); }
class DiagnosticSettingsImpl extends CreatableResourcesImpl<DiagnosticSetting, DiagnosticSettingImpl, DiagnosticSettingsResourceInner> implements DiagnosticSettings { private final ClientLogger logger = new ClientLogger(getClass()); private final MonitorManager manager; public DiagnosticSettingsImpl(final MonitorManager manager) { this.manager = manager; } @Override public DiagnosticSettingImpl define(String name) { return wrapModel(name); } @Override protected DiagnosticSettingImpl wrapModel(String name) { DiagnosticSettingsResourceInner inner = new DiagnosticSettingsResourceInner(); return new DiagnosticSettingImpl(name, inner, this.manager()); } @Override protected DiagnosticSettingImpl wrapModel(DiagnosticSettingsResourceInner inner) { if (inner == null) { return null; } return new DiagnosticSettingImpl(inner.name(), inner, this.manager()); } @Override public MonitorManager manager() { return this.manager; } public DiagnosticSettingsOperationsClient inner() { return this.manager().serviceClient().getDiagnosticSettingsOperations(); } @Override public List<DiagnosticSettingsCategory> listCategoriesByResource(String resourceId) { List<DiagnosticSettingsCategory> categories = new ArrayList<>(); PagedIterable<DiagnosticSettingsCategoryResourceInner> collection = this.manager().serviceClient().getDiagnosticSettingsCategories().list(ResourceUtils.encodeResourceId(resourceId)); if (collection != null) { for (DiagnosticSettingsCategoryResourceInner category : collection) { categories.add(new DiagnosticSettingsCategoryImpl(category)); } } return categories; } @Override public PagedFlux<DiagnosticSettingsCategory> listCategoriesByResourceAsync(String resourceId) { return PagedConverter.mapPage(this .manager .serviceClient() .getDiagnosticSettingsCategories() .listAsync(ResourceUtils.encodeResourceId(resourceId)), DiagnosticSettingsCategoryImpl::new); } @Override public DiagnosticSettingsCategory getCategory(String resourceId, String name) { return new DiagnosticSettingsCategoryImpl( this.manager().serviceClient().getDiagnosticSettingsCategories().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSettingsCategory> getCategoryAsync(String resourceId, String name) { return this .manager() .serviceClient() .getDiagnosticSettingsCategories() .getAsync(ResourceUtils.encodeResourceId(resourceId), name) .map(DiagnosticSettingsCategoryImpl::new); } @Override public PagedIterable<DiagnosticSetting> listByResource(String resourceId) { return new PagedIterable<>(this.listByResourceAsync(resourceId)); } @Override public PagedFlux<DiagnosticSetting> listByResourceAsync(String resourceId) { return PagedConverter.mapPage( this .manager() .serviceClient() .getDiagnosticSettingsOperations() .listAsync(ResourceUtils.encodeResourceId(resourceId)), inner -> new DiagnosticSettingImpl(inner.name(), inner, manager)); } @Override public void delete(String resourceId, String name) { this.manager().serviceClient().getDiagnosticSettingsOperations().delete(ResourceUtils.encodeResourceId(resourceId), name); } @Override public Mono<Void> deleteAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().deleteAsync(ResourceUtils.encodeResourceId(resourceId), name); } @Override public DiagnosticSetting get(String resourceId, String name) { return wrapModel(this.manager().serviceClient().getDiagnosticSettingsOperations().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSetting> getAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(ResourceUtils.encodeResourceId(resourceId), name).map(this::wrapModel); } @Override public Mono<Void> deleteByIdAsync(String id) { return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)); } @Override public Flux<String> deleteByIdsAsync(Collection<String> ids) { if (CoreUtils.isNullOrEmpty(ids)) { return Flux.empty(); } return Flux.fromIterable(ids) .flatMapDelayError(id -> deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).then(Mono.just(id)), 32, 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); } @Override public Flux<String> deleteByIdsAsync(String... ids) { return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids))); } @Override public void deleteByIds(Collection<String> ids) { if (ids != null && !ids.isEmpty()) { this.deleteByIdsAsync(ids).blockLast(); } } @Override public void deleteByIds(String... ids) { this.deleteByIds(new ArrayList<>(Arrays.asList(ids))); } @Override public DiagnosticSetting getById(String id) { return wrapModel(this.inner().get(getResourceIdFromSettingsId(id), getNameFromSettingsId(id))); } @Override public Mono<DiagnosticSetting> getByIdAsync(String id) { return this.inner().getAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).map(this::wrapModel); } private String getResourceIdFromSettingsId(String diagnosticSettingId) { diagnosticSettingId = ResourceUtils.encodeResourceId(diagnosticSettingId); if (diagnosticSettingId == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Parameter 'resourceId' is required and cannot be null.")); } int dsIdx = diagnosticSettingId.lastIndexOf(DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI); if (dsIdx == -1) { throw logger.logExceptionAsError(new IllegalArgumentException( "Parameter 'resourceId' does not represent a valid Diagnostic Settings resource Id [" + diagnosticSettingId + "].")); } return diagnosticSettingId.substring(0, dsIdx); } }
class DiagnosticSettingsImpl extends CreatableResourcesImpl<DiagnosticSetting, DiagnosticSettingImpl, DiagnosticSettingsResourceInner> implements DiagnosticSettings { private final ClientLogger logger = new ClientLogger(getClass()); private final MonitorManager manager; public DiagnosticSettingsImpl(final MonitorManager manager) { this.manager = manager; } @Override public DiagnosticSettingImpl define(String name) { return wrapModel(name); } @Override protected DiagnosticSettingImpl wrapModel(String name) { DiagnosticSettingsResourceInner inner = new DiagnosticSettingsResourceInner(); return new DiagnosticSettingImpl(name, inner, this.manager()); } @Override protected DiagnosticSettingImpl wrapModel(DiagnosticSettingsResourceInner inner) { if (inner == null) { return null; } return new DiagnosticSettingImpl(inner.name(), inner, this.manager()); } @Override public MonitorManager manager() { return this.manager; } public DiagnosticSettingsOperationsClient inner() { return this.manager().serviceClient().getDiagnosticSettingsOperations(); } @Override public List<DiagnosticSettingsCategory> listCategoriesByResource(String resourceId) { List<DiagnosticSettingsCategory> categories = new ArrayList<>(); PagedIterable<DiagnosticSettingsCategoryResourceInner> collection = this.manager().serviceClient().getDiagnosticSettingsCategories().list(ResourceUtils.encodeResourceId(resourceId)); if (collection != null) { for (DiagnosticSettingsCategoryResourceInner category : collection) { categories.add(new DiagnosticSettingsCategoryImpl(category)); } } return categories; } @Override public PagedFlux<DiagnosticSettingsCategory> listCategoriesByResourceAsync(String resourceId) { return PagedConverter.mapPage(this .manager .serviceClient() .getDiagnosticSettingsCategories() .listAsync(ResourceUtils.encodeResourceId(resourceId)), DiagnosticSettingsCategoryImpl::new); } @Override public DiagnosticSettingsCategory getCategory(String resourceId, String name) { return new DiagnosticSettingsCategoryImpl( this.manager().serviceClient().getDiagnosticSettingsCategories().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSettingsCategory> getCategoryAsync(String resourceId, String name) { return this .manager() .serviceClient() .getDiagnosticSettingsCategories() .getAsync(ResourceUtils.encodeResourceId(resourceId), name) .map(DiagnosticSettingsCategoryImpl::new); } @Override public PagedIterable<DiagnosticSetting> listByResource(String resourceId) { return new PagedIterable<>(this.listByResourceAsync(resourceId)); } @Override public PagedFlux<DiagnosticSetting> listByResourceAsync(String resourceId) { return PagedConverter.mapPage( this .manager() .serviceClient() .getDiagnosticSettingsOperations() .listAsync(ResourceUtils.encodeResourceId(resourceId)), inner -> new DiagnosticSettingImpl(inner.name(), inner, manager)); } @Override public void delete(String resourceId, String name) { this.manager().serviceClient().getDiagnosticSettingsOperations().delete(ResourceUtils.encodeResourceId(resourceId), name); } @Override public Mono<Void> deleteAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().deleteAsync(ResourceUtils.encodeResourceId(resourceId), name); } @Override public DiagnosticSetting get(String resourceId, String name) { return wrapModel(this.manager().serviceClient().getDiagnosticSettingsOperations().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSetting> getAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(ResourceUtils.encodeResourceId(resourceId), name).map(this::wrapModel); } @Override public Mono<Void> deleteByIdAsync(String id) { return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)); } @Override public Flux<String> deleteByIdsAsync(Collection<String> ids) { if (CoreUtils.isNullOrEmpty(ids)) { return Flux.empty(); } return Flux.fromIterable(ids) .flatMapDelayError(id -> deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).then(Mono.just(id)), 32, 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); } @Override public Flux<String> deleteByIdsAsync(String... ids) { return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids))); } @Override public void deleteByIds(Collection<String> ids) { if (ids != null && !ids.isEmpty()) { this.deleteByIdsAsync(ids).blockLast(); } } @Override public void deleteByIds(String... ids) { this.deleteByIds(new ArrayList<>(Arrays.asList(ids))); } @Override public DiagnosticSetting getById(String id) { return wrapModel(this.inner().get(getResourceIdFromSettingsId(id), getNameFromSettingsId(id))); } @Override public Mono<DiagnosticSetting> getByIdAsync(String id) { return this.inner().getAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).map(this::wrapModel); } /** * Get the resourceID from the diagnostic setting ID, with proper encoding. * * @param diagnosticSettingId ID of the diagnostic setting resource * @return properly encoded resourceID of the diagnostic setting */ private String getResourceIdFromSettingsId(String diagnosticSettingId) { return getResourceIdFromSettingsId(diagnosticSettingId, true); } /** * Get the resourceID from the diagnostic setting ID. * * @param diagnosticSettingId ID of the diagnostic setting resource * @param encodeResourceId whether to ensure the resourceID is properly encoded * @return resourceID of the diagnostic setting */ private String getResourceIdFromSettingsId(String diagnosticSettingId, boolean encodeResourceId) { if (diagnosticSettingId == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Parameter 'resourceId' is required and cannot be null.")); } if (encodeResourceId) { diagnosticSettingId = ResourceUtils.encodeResourceId(diagnosticSettingId); } int dsIdx = diagnosticSettingId.lastIndexOf(DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI); if (dsIdx == -1) { throw logger.logExceptionAsError(new IllegalArgumentException( "Parameter 'resourceId' does not represent a valid Diagnostic Settings resource Id [" + diagnosticSettingId + "].")); } return diagnosticSettingId.substring(0, dsIdx); } /** * Get raw diagnostic setting name from id. * * @param diagnosticSettingId ID of the diagnostic settting * @return raw name of the diagnostic setting */ }
can we use a low cost tier? it should have a free tier.
public void testCreateWebPubSubResource() { WebPubSubResource webPubSubResource = null; try { String resourceName = "webpubsub" + randomPadding(); webPubSubResource = webPubSubManager.webPubSubs() .define(resourceName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new ResourceSku().withName("Premium_P1").withCapacity(1).withTier(WebPubSubSkuTier.PREMIUM)) .withTls(new WebPubSubTlsSettings().withClientCertEnabled(false)) .withNetworkACLs(new WebPubSubNetworkACLs() .withDefaultAction(AclAction.DENY) .withPublicNetwork(new NetworkAcl().withAllow( Arrays.asList(WebPubSubRequestType.SERVER_CONNECTION, WebPubSubRequestType.CLIENT_CONNECTION, WebPubSubRequestType.RESTAPI, WebPubSubRequestType.TRACE) )) .withPrivateEndpoints(Collections.emptyList()) ) .withDisableAadAuth(false) .withDisableLocalAuth(false) .withPublicNetworkAccess("Enabled") .create(); webPubSubResource.refresh(); Assertions.assertEquals(webPubSubResource.name(), resourceName); Assertions.assertEquals(webPubSubResource.name(), webPubSubManager.webPubSubs().getById(webPubSubResource.id()).name()); Assertions.assertTrue(webPubSubManager.webPubSubs().list().stream().count() > 0); } finally { if (webPubSubResource != null) { webPubSubManager.webPubSubs().deleteById(webPubSubResource.id()); } } }
.withSku(new ResourceSku().withName("Premium_P1").withCapacity(1).withTier(WebPubSubSkuTier.PREMIUM))
public void testCreateWebPubSubResource() { WebPubSubResource webPubSubResource = null; try { String resourceName = "webpubsub" + randomPadding(); webPubSubResource = webPubSubManager.webPubSubs() .define(resourceName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new ResourceSku().withName("Free_F1").withCapacity(1).withTier(WebPubSubSkuTier.FREE)) .create(); webPubSubResource.refresh(); Assertions.assertEquals(webPubSubResource.name(), resourceName); Assertions.assertEquals(webPubSubResource.name(), webPubSubManager.webPubSubs().getById(webPubSubResource.id()).name()); Assertions.assertTrue(webPubSubManager.webPubSubs().list().stream().count() > 0); } finally { if (webPubSubResource != null) { webPubSubManager.webPubSubs().deleteById(webPubSubResource.id()); } } }
class WebPubSubManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST2; private String resourceGroupName = "rg" + randomPadding(); private WebPubSubManager webPubSubManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); webPubSubManager = WebPubSubManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class WebPubSubManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST2; private String resourceGroupName = "rg" + randomPadding(); private WebPubSubManager webPubSubManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); webPubSubManager = WebPubSubManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
remove if not needed
public void testCreateWebPubSubResource() { WebPubSubResource webPubSubResource = null; try { String resourceName = "webpubsub" + randomPadding(); webPubSubResource = webPubSubManager.webPubSubs() .define(resourceName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new ResourceSku().withName("Premium_P1").withCapacity(1).withTier(WebPubSubSkuTier.PREMIUM)) .withTls(new WebPubSubTlsSettings().withClientCertEnabled(false)) .withNetworkACLs(new WebPubSubNetworkACLs() .withDefaultAction(AclAction.DENY) .withPublicNetwork(new NetworkAcl().withAllow( Arrays.asList(WebPubSubRequestType.SERVER_CONNECTION, WebPubSubRequestType.CLIENT_CONNECTION, WebPubSubRequestType.RESTAPI, WebPubSubRequestType.TRACE) )) .withPrivateEndpoints(Collections.emptyList()) ) .withDisableAadAuth(false) .withDisableLocalAuth(false) .withPublicNetworkAccess("Enabled") .create(); webPubSubResource.refresh(); Assertions.assertEquals(webPubSubResource.name(), resourceName); Assertions.assertEquals(webPubSubResource.name(), webPubSubManager.webPubSubs().getById(webPubSubResource.id()).name()); Assertions.assertTrue(webPubSubManager.webPubSubs().list().stream().count() > 0); } finally { if (webPubSubResource != null) { webPubSubManager.webPubSubs().deleteById(webPubSubResource.id()); } } }
.withPrivateEndpoints(Collections.emptyList())
public void testCreateWebPubSubResource() { WebPubSubResource webPubSubResource = null; try { String resourceName = "webpubsub" + randomPadding(); webPubSubResource = webPubSubManager.webPubSubs() .define(resourceName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new ResourceSku().withName("Free_F1").withCapacity(1).withTier(WebPubSubSkuTier.FREE)) .create(); webPubSubResource.refresh(); Assertions.assertEquals(webPubSubResource.name(), resourceName); Assertions.assertEquals(webPubSubResource.name(), webPubSubManager.webPubSubs().getById(webPubSubResource.id()).name()); Assertions.assertTrue(webPubSubManager.webPubSubs().list().stream().count() > 0); } finally { if (webPubSubResource != null) { webPubSubManager.webPubSubs().deleteById(webPubSubResource.id()); } } }
class WebPubSubManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST2; private String resourceGroupName = "rg" + randomPadding(); private WebPubSubManager webPubSubManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); webPubSubManager = WebPubSubManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class WebPubSubManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST2; private String resourceGroupName = "rg" + randomPadding(); private WebPubSubManager webPubSubManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); webPubSubManager = WebPubSubManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Redundant parameter settings have been removed and `Sku` type has been changed to `Free` in the new version.
public void testCreateWebPubSubResource() { WebPubSubResource webPubSubResource = null; try { String resourceName = "webpubsub" + randomPadding(); webPubSubResource = webPubSubManager.webPubSubs() .define(resourceName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new ResourceSku().withName("Premium_P1").withCapacity(1).withTier(WebPubSubSkuTier.PREMIUM)) .withTls(new WebPubSubTlsSettings().withClientCertEnabled(false)) .withNetworkACLs(new WebPubSubNetworkACLs() .withDefaultAction(AclAction.DENY) .withPublicNetwork(new NetworkAcl().withAllow( Arrays.asList(WebPubSubRequestType.SERVER_CONNECTION, WebPubSubRequestType.CLIENT_CONNECTION, WebPubSubRequestType.RESTAPI, WebPubSubRequestType.TRACE) )) .withPrivateEndpoints(Collections.emptyList()) ) .withDisableAadAuth(false) .withDisableLocalAuth(false) .withPublicNetworkAccess("Enabled") .create(); webPubSubResource.refresh(); Assertions.assertEquals(webPubSubResource.name(), resourceName); Assertions.assertEquals(webPubSubResource.name(), webPubSubManager.webPubSubs().getById(webPubSubResource.id()).name()); Assertions.assertTrue(webPubSubManager.webPubSubs().list().stream().count() > 0); } finally { if (webPubSubResource != null) { webPubSubManager.webPubSubs().deleteById(webPubSubResource.id()); } } }
.withPrivateEndpoints(Collections.emptyList())
public void testCreateWebPubSubResource() { WebPubSubResource webPubSubResource = null; try { String resourceName = "webpubsub" + randomPadding(); webPubSubResource = webPubSubManager.webPubSubs() .define(resourceName) .withRegion(REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new ResourceSku().withName("Free_F1").withCapacity(1).withTier(WebPubSubSkuTier.FREE)) .create(); webPubSubResource.refresh(); Assertions.assertEquals(webPubSubResource.name(), resourceName); Assertions.assertEquals(webPubSubResource.name(), webPubSubManager.webPubSubs().getById(webPubSubResource.id()).name()); Assertions.assertTrue(webPubSubManager.webPubSubs().list().stream().count() > 0); } finally { if (webPubSubResource != null) { webPubSubManager.webPubSubs().deleteById(webPubSubResource.id()); } } }
class WebPubSubManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST2; private String resourceGroupName = "rg" + randomPadding(); private WebPubSubManager webPubSubManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); webPubSubManager = WebPubSubManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class WebPubSubManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_EAST2; private String resourceGroupName = "rg" + randomPadding(); private WebPubSubManager webPubSubManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); webPubSubManager = WebPubSubManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
do we need to validate whether exception is CosmosException?
public Mono<ShouldRetryResult> shouldRetry(Exception e) { if (this.request == null) { logger.error("onBeforeSendRequest has not been invoked with the MetadataRequestRetryPolicy..."); return Mono.just(ShouldRetryResult.error(e)); } CosmosException cosmosException = Utils.as(e, CosmosException.class); if (shouldMarkRegionAsUnavailable(cosmosException)) { URI locationEndpointToRoute = request.requestContext.locationEndpointToRoute; if (request.isReadOnlyRequest()) { this.globalEndpointManager.markEndpointUnavailableForRead(locationEndpointToRoute); } else { this.globalEndpointManager.markEndpointUnavailableForWrite(locationEndpointToRoute); } } return Mono.just(ShouldRetryResult.error(cosmosException)); }
CosmosException cosmosException = Utils.as(e, CosmosException.class);
public Mono<ShouldRetryResult> shouldRetry(Exception e) { return webExceptionRetryPolicy.shouldRetry(e).flatMap(shouldRetryResult -> { if (!shouldRetryResult.shouldRetry) { if (this.request == null || this.webExceptionRetryPolicy == null) { logger.error("onBeforeSendRequest has not been invoked with the MetadataRequestRetryPolicy..."); return Mono.just(ShouldRetryResult.error(e)); } if (!(e instanceof CosmosException)) { logger.debug("exception is not an instance of CosmosException..."); return Mono.just(ShouldRetryResult.error(e)); } CosmosException cosmosException = Utils.as(e, CosmosException.class); if (shouldMarkRegionAsUnavailable(cosmosException)) { URI locationEndpointToRoute = request.requestContext.locationEndpointToRoute; if (request.isReadOnlyRequest()) { this.globalEndpointManager.markEndpointUnavailableForRead(locationEndpointToRoute); } else { this.globalEndpointManager.markEndpointUnavailableForWrite(locationEndpointToRoute); } } return Mono.just(ShouldRetryResult.error(cosmosException)); } return Mono.just(shouldRetryResult); }); }
class MetadataRequestRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(MetadataRequestRetryPolicy.class); private final GlobalEndpointManager globalEndpointManager; private RxDocumentServiceRequest request; public MetadataRequestRetryPolicy(GlobalEndpointManager globalEndpointManager) { this.globalEndpointManager = globalEndpointManager; } public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; } private static boolean shouldMarkRegionAsUnavailable(CosmosException exception) { if (WebExceptionUtility.isNetworkFailure(exception)) { return Exceptions.isSubStatusCode(exception, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE) || Exceptions.isSubStatusCode(exception, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } return false; } @Override @Override public RetryContext getRetryContext() { return null; } }
class MetadataRequestRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(MetadataRequestRetryPolicy.class); private final GlobalEndpointManager globalEndpointManager; private RxDocumentServiceRequest request; private WebExceptionRetryPolicy webExceptionRetryPolicy; public MetadataRequestRetryPolicy(GlobalEndpointManager globalEndpointManager) { this.globalEndpointManager = globalEndpointManager; } public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.webExceptionRetryPolicy = new WebExceptionRetryPolicy(BridgeInternal.getRetryContext(request.requestContext.cosmosDiagnostics)); } private boolean shouldMarkRegionAsUnavailable(CosmosException exception) { if (!(request.isAddressRefresh() || request.isMetadataRequest())) { return false; } if (WebExceptionUtility.isNetworkFailure(exception)) { return Exceptions.isSubStatusCode(exception, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } return false; } @Override @Override public RetryContext getRetryContext() { return null; } }
why we are changing `globalCommittedSelectedLSN` `quorumSelectedStoreResponse` etc?
private void handleGoneException(RxDocumentServiceRequest request, Exception exception) { if (request.requestContext == null) { return; } if (exception instanceof PartitionIsMigratingException) { request.forceCollectionRoutingMapRefresh = true; request.requestContext.forceRefreshAddressCache = true; } else if (exception instanceof InvalidPartitionException) { request.forceNameCacheRefresh = true; request.requestContext.quorumSelectedLSN = -1; request.requestContext.resolvedPartitionKeyRange = null; request.requestContext.quorumSelectedStoreResponse = null; request.requestContext.globalCommittedSelectedLSN = -1; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { request.requestContext.resolvedPartitionKeyRange = null; request.requestContext.quorumSelectedLSN = -1; request.requestContext.quorumSelectedStoreResponse = null; request.forcePartitionKeyRangeRefresh = true; } else if (exception instanceof GoneException) { request.requestContext.forceRefreshAddressCache = true; } else if (exception instanceof PartitionKeyRangeGoneException) { request.forcePartitionKeyRangeRefresh = true; request.requestContext.forceRefreshAddressCache = true; request.requestContext.resolvedPartitionKeyRange = null; request.requestContext.quorumSelectedLSN = -1; request.requestContext.quorumSelectedStoreResponse = null; } }
request.requestContext.globalCommittedSelectedLSN = -1;
private void handleGoneException(RxDocumentServiceRequest request, Exception exception) { if (request.requestContext == null) { return; } if (exception instanceof PartitionIsMigratingException) { request.forceCollectionRoutingMapRefresh = true; request.requestContext.forceRefreshAddressCache = true; } else if (exception instanceof InvalidPartitionException) { request.forceNameCacheRefresh = true; request.requestContext.resolvedPartitionKeyRange = null; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { request.requestContext.resolvedPartitionKeyRange = null; request.forcePartitionKeyRangeRefresh = true; request.requestContext.forceRefreshAddressCache = true; } else if (exception instanceof GoneException) { request.requestContext.forceRefreshAddressCache = true; } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } final RxDocumentServiceRequest serviceRequest = requestRecord.args().serviceRequest(); requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.SERVER_GENERATED_408); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } } private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } final RxDocumentServiceRequest serviceRequest = requestRecord.args().serviceRequest(); requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest, cause); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest, cause); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest, cause); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest, cause); break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.SERVER_GENERATED_408); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } } private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
Fixed in the next iteration.
private void handleGoneException(RxDocumentServiceRequest request, Exception exception) { if (request.requestContext == null) { return; } if (exception instanceof PartitionIsMigratingException) { request.forceCollectionRoutingMapRefresh = true; request.requestContext.forceRefreshAddressCache = true; } else if (exception instanceof InvalidPartitionException) { request.forceNameCacheRefresh = true; request.requestContext.quorumSelectedLSN = -1; request.requestContext.resolvedPartitionKeyRange = null; request.requestContext.quorumSelectedStoreResponse = null; request.requestContext.globalCommittedSelectedLSN = -1; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { request.requestContext.resolvedPartitionKeyRange = null; request.requestContext.quorumSelectedLSN = -1; request.requestContext.quorumSelectedStoreResponse = null; request.forcePartitionKeyRangeRefresh = true; } else if (exception instanceof GoneException) { request.requestContext.forceRefreshAddressCache = true; } else if (exception instanceof PartitionKeyRangeGoneException) { request.forcePartitionKeyRangeRefresh = true; request.requestContext.forceRefreshAddressCache = true; request.requestContext.resolvedPartitionKeyRange = null; request.requestContext.quorumSelectedLSN = -1; request.requestContext.quorumSelectedStoreResponse = null; } }
request.requestContext.globalCommittedSelectedLSN = -1;
private void handleGoneException(RxDocumentServiceRequest request, Exception exception) { if (request.requestContext == null) { return; } if (exception instanceof PartitionIsMigratingException) { request.forceCollectionRoutingMapRefresh = true; request.requestContext.forceRefreshAddressCache = true; } else if (exception instanceof InvalidPartitionException) { request.forceNameCacheRefresh = true; request.requestContext.resolvedPartitionKeyRange = null; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { request.requestContext.resolvedPartitionKeyRange = null; request.forcePartitionKeyRangeRefresh = true; request.requestContext.forceRefreshAddressCache = true; } else if (exception instanceof GoneException) { request.requestContext.forceRefreshAddressCache = true; } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } final RxDocumentServiceRequest serviceRequest = requestRecord.args().serviceRequest(); requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest); break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.SERVER_GENERATED_408); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } } private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } final RxDocumentServiceRequest serviceRequest = requestRecord.args().serviceRequest(); requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest, cause); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest, cause); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest, cause); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; handleGoneException(serviceRequest, cause); rntbdConnectionStateListener.attemptBackgroundAddressRefresh(serviceRequest, cause); break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.SERVER_GENERATED_408); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } } private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
Fixed in next iteration.
public Mono<ShouldRetryResult> shouldRetry(Exception e) { if (this.request == null) { logger.error("onBeforeSendRequest has not been invoked with the MetadataRequestRetryPolicy..."); return Mono.just(ShouldRetryResult.error(e)); } CosmosException cosmosException = Utils.as(e, CosmosException.class); if (shouldMarkRegionAsUnavailable(cosmosException)) { URI locationEndpointToRoute = request.requestContext.locationEndpointToRoute; if (request.isReadOnlyRequest()) { this.globalEndpointManager.markEndpointUnavailableForRead(locationEndpointToRoute); } else { this.globalEndpointManager.markEndpointUnavailableForWrite(locationEndpointToRoute); } } return Mono.just(ShouldRetryResult.error(cosmosException)); }
CosmosException cosmosException = Utils.as(e, CosmosException.class);
public Mono<ShouldRetryResult> shouldRetry(Exception e) { return webExceptionRetryPolicy.shouldRetry(e).flatMap(shouldRetryResult -> { if (!shouldRetryResult.shouldRetry) { if (this.request == null || this.webExceptionRetryPolicy == null) { logger.error("onBeforeSendRequest has not been invoked with the MetadataRequestRetryPolicy..."); return Mono.just(ShouldRetryResult.error(e)); } if (!(e instanceof CosmosException)) { logger.debug("exception is not an instance of CosmosException..."); return Mono.just(ShouldRetryResult.error(e)); } CosmosException cosmosException = Utils.as(e, CosmosException.class); if (shouldMarkRegionAsUnavailable(cosmosException)) { URI locationEndpointToRoute = request.requestContext.locationEndpointToRoute; if (request.isReadOnlyRequest()) { this.globalEndpointManager.markEndpointUnavailableForRead(locationEndpointToRoute); } else { this.globalEndpointManager.markEndpointUnavailableForWrite(locationEndpointToRoute); } } return Mono.just(ShouldRetryResult.error(cosmosException)); } return Mono.just(shouldRetryResult); }); }
class MetadataRequestRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(MetadataRequestRetryPolicy.class); private final GlobalEndpointManager globalEndpointManager; private RxDocumentServiceRequest request; public MetadataRequestRetryPolicy(GlobalEndpointManager globalEndpointManager) { this.globalEndpointManager = globalEndpointManager; } public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; } private static boolean shouldMarkRegionAsUnavailable(CosmosException exception) { if (WebExceptionUtility.isNetworkFailure(exception)) { return Exceptions.isSubStatusCode(exception, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE) || Exceptions.isSubStatusCode(exception, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } return false; } @Override @Override public RetryContext getRetryContext() { return null; } }
class MetadataRequestRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(MetadataRequestRetryPolicy.class); private final GlobalEndpointManager globalEndpointManager; private RxDocumentServiceRequest request; private WebExceptionRetryPolicy webExceptionRetryPolicy; public MetadataRequestRetryPolicy(GlobalEndpointManager globalEndpointManager) { this.globalEndpointManager = globalEndpointManager; } public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.webExceptionRetryPolicy = new WebExceptionRetryPolicy(BridgeInternal.getRetryContext(request.requestContext.cosmosDiagnostics)); } private boolean shouldMarkRegionAsUnavailable(CosmosException exception) { if (!(request.isAddressRefresh() || request.isMetadataRequest())) { return false; } if (WebExceptionUtility.isNetworkFailure(exception)) { return Exceptions.isSubStatusCode(exception, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } return false; } @Override @Override public RetryContext getRetryContext() { return null; } }
Does backend really need this?
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .withProperties(new AccountProperties() .withCustomSubDomainName(accountName) .withNetworkAcls(new NetworkRuleSet() .withDefaultAction(NetworkRuleAction.ALLOW)) .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) ) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
.withKind("CognitiveServices")
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Redundant parameter settings have been removed in the new version.
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .withProperties(new AccountProperties() .withCustomSubDomainName(accountName) .withNetworkAcls(new NetworkRuleSet() .withDefaultAction(NetworkRuleAction.ALLOW)) .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) ) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
.withKind("CognitiveServices")
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Is `withKind("CognitiveServices")` required?
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .withProperties(new AccountProperties() .withCustomSubDomainName(accountName) .withNetworkAcls(new NetworkRuleSet() .withDefaultAction(NetworkRuleAction.ALLOW)) .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) ) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
.withKind("CognitiveServices")
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
I tried to remove `withKind("CognitiveServices")`, but an exception occurs. ![image](https://github.com/Azure/azure-sdk-for-java/assets/74638143/30c1a070-895f-4a67-a6e6-00376430e3bd) So it is required.
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .withProperties(new AccountProperties() .withCustomSubDomainName(accountName) .withNetworkAcls(new NetworkRuleSet() .withDefaultAction(NetworkRuleAction.ALLOW)) .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) ) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
.withKind("CognitiveServices")
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Thanks. Crazy backend, as if it does not know what service it is...
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .withProperties(new AccountProperties() .withCustomSubDomainName(accountName) .withNetworkAcls(new NetworkRuleSet() .withDefaultAction(NetworkRuleAction.ALLOW)) .withPublicNetworkAccess(PublicNetworkAccess.ENABLED) ) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
.withKind("CognitiveServices")
public void testCreateAccount() { Account account = null; try { String accountName = "account" + randomPadding(); account = cognitiveServicesManager.accounts() .define(accountName) .withExistingResourceGroup(resourceGroupName) .withRegion(REGION) .withKind("CognitiveServices") .withSku(new Sku().withName("S0")) .create(); account.refresh(); Assertions.assertEquals(account.name(), accountName); Assertions.assertEquals(account.name(), cognitiveServicesManager.accounts().getById(account.id()).name()); Assertions.assertTrue(cognitiveServicesManager.accounts().list().stream().count() > 0); } finally { if (account != null) { cognitiveServicesManager.accounts().deleteById(account.id()); } } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class CognitiveServicesManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST3; private String resourceGroupName = "rg" + randomPadding(); private CognitiveServicesManager cognitiveServicesManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); cognitiveServicesManager = CognitiveServicesManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Can we use larger time range (e.g. 7 days or 30 days)? This assert here depends on env in that subscription. 1 day may be too short to guarantee that there were a change.
public void test() { Assertions.assertTrue(azureChangeAnalysisManager.changes() .list(OffsetDateTime.now().minusDays(1), OffsetDateTime.now().plusDays(1)).stream().count() > 0); }
.list(OffsetDateTime.now().minusDays(1), OffsetDateTime.now().plusDays(1)).stream().count() > 0);
public void test() { OffsetDateTime nowDateTime = OffsetDateTime.now(); Assertions.assertTrue(azureChangeAnalysisManager.changes() .list(nowDateTime.minusWeeks(2), nowDateTime).stream().count() > 0); }
class AzureChangeAnalysisManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private AzureChangeAnalysisManager azureChangeAnalysisManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); azureChangeAnalysisManager = AzureChangeAnalysisManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class AzureChangeAnalysisManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private AzureChangeAnalysisManager azureChangeAnalysisManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); azureChangeAnalysisManager = AzureChangeAnalysisManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
Fixed in the new version.
public void test() { Assertions.assertTrue(azureChangeAnalysisManager.changes() .list(OffsetDateTime.now().minusDays(1), OffsetDateTime.now().plusDays(1)).stream().count() > 0); }
.list(OffsetDateTime.now().minusDays(1), OffsetDateTime.now().plusDays(1)).stream().count() > 0);
public void test() { OffsetDateTime nowDateTime = OffsetDateTime.now(); Assertions.assertTrue(azureChangeAnalysisManager.changes() .list(nowDateTime.minusWeeks(2), nowDateTime).stream().count() > 0); }
class AzureChangeAnalysisManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private AzureChangeAnalysisManager azureChangeAnalysisManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); azureChangeAnalysisManager = AzureChangeAnalysisManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class AzureChangeAnalysisManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private AzureChangeAnalysisManager azureChangeAnalysisManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); azureChangeAnalysisManager = AzureChangeAnalysisManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
I didn't see how changing from "1 day in future" to "7 day in future" would help. I don't think the RP can forecast the future changes.
public void test() { Assertions.assertTrue(azureChangeAnalysisManager.changes() .list(OffsetDateTime.now().minusDays(1), OffsetDateTime.now().plusDays(1)).stream().count() > 0); }
.list(OffsetDateTime.now().minusDays(1), OffsetDateTime.now().plusDays(1)).stream().count() > 0);
public void test() { OffsetDateTime nowDateTime = OffsetDateTime.now(); Assertions.assertTrue(azureChangeAnalysisManager.changes() .list(nowDateTime.minusWeeks(2), nowDateTime).stream().count() > 0); }
class AzureChangeAnalysisManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private AzureChangeAnalysisManager azureChangeAnalysisManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); azureChangeAnalysisManager = AzureChangeAnalysisManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class AzureChangeAnalysisManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private AzureChangeAnalysisManager azureChangeAnalysisManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); azureChangeAnalysisManager = AzureChangeAnalysisManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
The time range has been fixed to within the past two weeks in the new version.
public void test() { Assertions.assertTrue(azureChangeAnalysisManager.changes() .list(OffsetDateTime.now().minusDays(1), OffsetDateTime.now().plusDays(1)).stream().count() > 0); }
.list(OffsetDateTime.now().minusDays(1), OffsetDateTime.now().plusDays(1)).stream().count() > 0);
public void test() { OffsetDateTime nowDateTime = OffsetDateTime.now(); Assertions.assertTrue(azureChangeAnalysisManager.changes() .list(nowDateTime.minusWeeks(2), nowDateTime).stream().count() > 0); }
class AzureChangeAnalysisManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private AzureChangeAnalysisManager azureChangeAnalysisManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); azureChangeAnalysisManager = AzureChangeAnalysisManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class AzureChangeAnalysisManagerTest extends TestBase { private static final Random RANDOM = new Random(); private static final Region REGION = Region.US_WEST2; private String resourceGroupName = "rg" + randomPadding(); private AzureChangeAnalysisManager azureChangeAnalysisManager; private ResourceManager resourceManager; private boolean testEnv; @Override public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); azureChangeAnalysisManager = AzureChangeAnalysisManager .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(); } } @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
The builder should already have a retry policy, won't this add a second one?
private void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { if (interceptorManager.isPlaybackMode()) { connectionString = FAKE_CONNECTION_STRING; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(new MockTokenCredential()) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-content-sha256")))); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); ConfigurationClientBuilder builder = new ConfigurationClientBuilder() .httpClient(httpClient) .credential(tokenCredential) .endpoint(endpoint) .serviceVersion(serviceVersion) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); builder = setHttpClient(httpClient, builder); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } client = builder.buildClient(); } }
.addPolicy(new RetryPolicy());
private void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { if (interceptorManager.isPlaybackMode()) { connectionString = FAKE_CONNECTION_STRING; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(new MockTokenCredential()) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); ConfigurationClientBuilder builder = new ConfigurationClientBuilder() .endpoint(endpoint) .credential(tokenCredential) .serviceVersion(serviceVersion); builder = setHttpClient(httpClient, builder); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } client = builder.buildClient(); } }
class AadCredentialTest extends TestProxyTestBase { private static ConfigurationClient client; private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; static String connectionString; static TokenCredential tokenCredential; ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) { if (interceptorManager.isRecordMode()) { return builder .httpClient(buildSyncAssertingClient(httpClient)); } else if (interceptorManager.isPlaybackMode()) { return builder .httpClient(buildSyncAssertingClient(interceptorManager.getPlaybackClient())); } return builder; } private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertSync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void aadAuthenticationAzConfigClient(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { setup(httpClient, serviceVersion); final String key = "newKey"; final String value = "newValue"; ConfigurationSetting addedSetting = client.setConfigurationSetting(key, null, value); Assertions.assertEquals(addedSetting.getKey(), key); Assertions.assertEquals(addedSetting.getValue(), value); } }
class AadCredentialTest extends TestProxyTestBase { private static ConfigurationClient client; private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; static String connectionString; static TokenCredential tokenCredential; ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) { if (interceptorManager.isPlaybackMode()) { return builder.httpClient(buildSyncAssertingClient(interceptorManager.getPlaybackClient())); } return builder.httpClient(buildSyncAssertingClient(httpClient)); } private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertSync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void aadAuthenticationAzConfigClient(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { setup(httpClient, serviceVersion); final String key = "newKey"; final String value = "newValue"; ConfigurationSetting addedSetting = client.setConfigurationSetting(key, null, value); Assertions.assertEquals(addedSetting.getKey(), key); Assertions.assertEquals(addedSetting.getValue(), value); } }
I don't think we need to include this anymore. This doesn't configure any allowed headers and query parameters anyways.
private void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { if (interceptorManager.isPlaybackMode()) { connectionString = FAKE_CONNECTION_STRING; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(new MockTokenCredential()) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-content-sha256")))); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); ConfigurationClientBuilder builder = new ConfigurationClientBuilder() .httpClient(httpClient) .credential(tokenCredential) .endpoint(endpoint) .serviceVersion(serviceVersion) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); builder = setHttpClient(httpClient, builder); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } client = builder.buildClient(); } }
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS));
private void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { if (interceptorManager.isPlaybackMode()) { connectionString = FAKE_CONNECTION_STRING; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(new MockTokenCredential()) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); ConfigurationClientBuilder builder = new ConfigurationClientBuilder() .endpoint(endpoint) .credential(tokenCredential) .serviceVersion(serviceVersion); builder = setHttpClient(httpClient, builder); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } client = builder.buildClient(); } }
class AadCredentialTest extends TestProxyTestBase { private static ConfigurationClient client; private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; static String connectionString; static TokenCredential tokenCredential; ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) { if (interceptorManager.isRecordMode()) { return builder .httpClient(buildSyncAssertingClient(httpClient)); } else if (interceptorManager.isPlaybackMode()) { return builder .httpClient(buildSyncAssertingClient(interceptorManager.getPlaybackClient())); } return builder; } private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertSync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void aadAuthenticationAzConfigClient(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { setup(httpClient, serviceVersion); final String key = "newKey"; final String value = "newValue"; ConfigurationSetting addedSetting = client.setConfigurationSetting(key, null, value); Assertions.assertEquals(addedSetting.getKey(), key); Assertions.assertEquals(addedSetting.getValue(), value); } }
class AadCredentialTest extends TestProxyTestBase { private static ConfigurationClient client; private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; static String connectionString; static TokenCredential tokenCredential; ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) { if (interceptorManager.isPlaybackMode()) { return builder.httpClient(buildSyncAssertingClient(interceptorManager.getPlaybackClient())); } return builder.httpClient(buildSyncAssertingClient(httpClient)); } private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertSync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void aadAuthenticationAzConfigClient(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { setup(httpClient, serviceVersion); final String key = "newKey"; final String value = "newValue"; ConfigurationSetting addedSetting = client.setConfigurationSetting(key, null, value); Assertions.assertEquals(addedSetting.getKey(), key); Assertions.assertEquals(addedSetting.getValue(), value); } }
Don't we want to add the asserting client when running LIVE test mode as well?
ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) { if (interceptorManager.isRecordMode()) { return builder .httpClient(buildSyncAssertingClient(httpClient)); } else if (interceptorManager.isPlaybackMode()) { return builder .httpClient(buildSyncAssertingClient(interceptorManager.getPlaybackClient())); } return builder; }
.httpClient(buildSyncAssertingClient(httpClient));
ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) { if (interceptorManager.isPlaybackMode()) { return builder.httpClient(buildSyncAssertingClient(interceptorManager.getPlaybackClient())); } return builder.httpClient(buildSyncAssertingClient(httpClient)); }
class AadCredentialTest extends TestProxyTestBase { private static ConfigurationClient client; private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; static String connectionString; static TokenCredential tokenCredential; private void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { if (interceptorManager.isPlaybackMode()) { connectionString = FAKE_CONNECTION_STRING; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(new MockTokenCredential()) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-content-sha256")))); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); ConfigurationClientBuilder builder = new ConfigurationClientBuilder() .httpClient(httpClient) .credential(tokenCredential) .endpoint(endpoint) .serviceVersion(serviceVersion) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); builder = setHttpClient(httpClient, builder); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } client = builder.buildClient(); } } private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertSync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void aadAuthenticationAzConfigClient(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { setup(httpClient, serviceVersion); final String key = "newKey"; final String value = "newValue"; ConfigurationSetting addedSetting = client.setConfigurationSetting(key, null, value); Assertions.assertEquals(addedSetting.getKey(), key); Assertions.assertEquals(addedSetting.getValue(), value); } }
class AadCredentialTest extends TestProxyTestBase { private static ConfigurationClient client; private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; static String connectionString; static TokenCredential tokenCredential; private void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { if (interceptorManager.isPlaybackMode()) { connectionString = FAKE_CONNECTION_STRING; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(new MockTokenCredential()) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); ConfigurationClientBuilder builder = new ConfigurationClientBuilder() .endpoint(endpoint) .credential(tokenCredential) .serviceVersion(serviceVersion); builder = setHttpClient(httpClient, builder); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } client = builder.buildClient(); } } private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertSync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void aadAuthenticationAzConfigClient(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { setup(httpClient, serviceVersion); final String key = "newKey"; final String value = "newValue"; ConfigurationSetting addedSetting = client.setConfigurationSetting(key, null, value); Assertions.assertEquals(addedSetting.getKey(), key); Assertions.assertEquals(addedSetting.getValue(), value); } }
Yea. It should also apply to LIVE mode as well. Updated.
ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) { if (interceptorManager.isRecordMode()) { return builder .httpClient(buildSyncAssertingClient(httpClient)); } else if (interceptorManager.isPlaybackMode()) { return builder .httpClient(buildSyncAssertingClient(interceptorManager.getPlaybackClient())); } return builder; }
.httpClient(buildSyncAssertingClient(httpClient));
ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) { if (interceptorManager.isPlaybackMode()) { return builder.httpClient(buildSyncAssertingClient(interceptorManager.getPlaybackClient())); } return builder.httpClient(buildSyncAssertingClient(httpClient)); }
class AadCredentialTest extends TestProxyTestBase { private static ConfigurationClient client; private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; static String connectionString; static TokenCredential tokenCredential; private void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { if (interceptorManager.isPlaybackMode()) { connectionString = FAKE_CONNECTION_STRING; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(new MockTokenCredential()) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-content-sha256")))); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); ConfigurationClientBuilder builder = new ConfigurationClientBuilder() .httpClient(httpClient) .credential(tokenCredential) .endpoint(endpoint) .serviceVersion(serviceVersion) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); builder = setHttpClient(httpClient, builder); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()); } client = builder.buildClient(); } } private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertSync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void aadAuthenticationAzConfigClient(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { setup(httpClient, serviceVersion); final String key = "newKey"; final String value = "newValue"; ConfigurationSetting addedSetting = client.setConfigurationSetting(key, null, value); Assertions.assertEquals(addedSetting.getKey(), key); Assertions.assertEquals(addedSetting.getValue(), value); } }
class AadCredentialTest extends TestProxyTestBase { private static ConfigurationClient client; private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; static String connectionString; static TokenCredential tokenCredential; private void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { if (interceptorManager.isPlaybackMode()) { connectionString = FAKE_CONNECTION_STRING; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(new MockTokenCredential()) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); ConfigurationClientBuilder builder = new ConfigurationClientBuilder() .endpoint(endpoint) .credential(tokenCredential) .serviceVersion(serviceVersion); builder = setHttpClient(httpClient, builder); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } client = builder.buildClient(); } } private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertSync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void aadAuthenticationAzConfigClient(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) { setup(httpClient, serviceVersion); final String key = "newKey"; final String value = "newValue"; ConfigurationSetting addedSetting = client.setConfigurationSetting(key, null, value); Assertions.assertEquals(addedSetting.getKey(), key); Assertions.assertEquals(addedSetting.getValue(), value); } }
```suggestion currentLine = outStream.toString(StandardCharsets.UTF_8); ```
private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); }
currentLine = outStream.toString(StandardCharsets.UTF_8.name());
private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); } }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); } }
should we use ".stripLeading()" to remove all leading whitespaces?
private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); }
if (split[1].startsWith(" ")) {
private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); } }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); } }
```suggestion try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { // return the values collected so far, as this could be because the server sent event is // split across two byte buffers and the last line is incomplete and will be continued in // the next byte buffer return Flux.fromIterable(values); } ```
private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); }
}
private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); } }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); } }
nvm. It is a method since Java 11.
private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); }
if (split[1].startsWith(" ")) {
private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); } }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); } }
My bad. My changes only apply to java 10+. Since we are targeting java 8. Will close this feedback.
private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); }
}
private Flux<T> mapByteBuffersToEvents() { return source .publishOn(Schedulers.boundedElastic()) .concatMap(byteBuffer -> { List<T> values = new ArrayList<>(); byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { String currentLine; try { currentLine = outStream.toString(StandardCharsets.UTF_8.name()); handleCurrentLine(currentLine, values); } catch (UnsupportedEncodingException | JsonProcessingException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); } else { outStream.write(currentByte); } } try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); } catch (IllegalStateException | JsonProcessingException e) { return Flux.fromIterable(values); } catch (UnsupportedEncodingException e) { return Flux.error(e); } return Flux.fromIterable(values); }).cache(); }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); } }
class OpenAIServerSentEvents<T> { private static final String STREAM_COMPLETION_EVENT = "data: [DONE]"; private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux<ByteBuffer> source; private final Class<T> type; private ByteArrayOutputStream outStream; private static final ObjectMapper SERIALIZER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); public OpenAIServerSentEvents(Flux<ByteBuffer> source, Class<T> type) { this.source = source; this.type = type; this.outStream = new ByteArrayOutputStream(); } public Flux<T> getEvents() { return mapByteBuffersToEvents(); } private void handleCurrentLine(String currentLine, List<T> values) throws JsonProcessingException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.equals(currentLine)) { return; } String[] split = currentLine.split(":", 2); if (split.length != 2) { throw new IllegalStateException("Invalid data format " + currentLine); } String dataValue = split[1]; if (split[1].startsWith(" ")) { dataValue = split[1].substring(1); } T value = SERIALIZER.readValue(dataValue, type); values.add(value); } }
`this.inner.deleteAsync` actually takes `resourceUri` and `name` as parameters. There's no delete methods that take `resourceGroupName` as required by `BatchDeletionImpl`. test coverage: https://github.com/Azure/azure-sdk-for-java/pull/35649/files#diff-80db7e9bf4f9660318589cf767653a167e8eb9bcbadf1d829360842ff67be696R436
public Flux<String> deleteByIdsAsync(Collection<String> ids) { if (CoreUtils.isNullOrEmpty(ids)) { return Flux.empty(); } return Flux.fromIterable(ids) .flatMapDelayError(id -> deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).then(Mono.just(id)), 32, 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); }
.subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler());
public Flux<String> deleteByIdsAsync(Collection<String> ids) { if (CoreUtils.isNullOrEmpty(ids)) { return Flux.empty(); } return Flux.fromIterable(ids) .flatMapDelayError(id -> deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).then(Mono.just(id)), 32, 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); }
class DiagnosticSettingsImpl extends CreatableResourcesImpl<DiagnosticSetting, DiagnosticSettingImpl, DiagnosticSettingsResourceInner> implements DiagnosticSettings { private final ClientLogger logger = new ClientLogger(getClass()); private final MonitorManager manager; public DiagnosticSettingsImpl(final MonitorManager manager) { this.manager = manager; } @Override public DiagnosticSettingImpl define(String name) { return wrapModel(name); } @Override protected DiagnosticSettingImpl wrapModel(String name) { DiagnosticSettingsResourceInner inner = new DiagnosticSettingsResourceInner(); return new DiagnosticSettingImpl(name, inner, this.manager()); } @Override protected DiagnosticSettingImpl wrapModel(DiagnosticSettingsResourceInner inner) { if (inner == null) { return null; } return new DiagnosticSettingImpl(inner.name(), inner, this.manager()); } @Override public MonitorManager manager() { return this.manager; } public DiagnosticSettingsOperationsClient inner() { return this.manager().serviceClient().getDiagnosticSettingsOperations(); } @Override public List<DiagnosticSettingsCategory> listCategoriesByResource(String resourceId) { List<DiagnosticSettingsCategory> categories = new ArrayList<>(); PagedIterable<DiagnosticSettingsCategoryResourceInner> collection = this.manager().serviceClient().getDiagnosticSettingsCategories().list(ResourceUtils.encodeResourceId(resourceId)); if (collection != null) { for (DiagnosticSettingsCategoryResourceInner category : collection) { categories.add(new DiagnosticSettingsCategoryImpl(category)); } } return categories; } @Override public PagedFlux<DiagnosticSettingsCategory> listCategoriesByResourceAsync(String resourceId) { return PagedConverter.mapPage(this .manager .serviceClient() .getDiagnosticSettingsCategories() .listAsync(ResourceUtils.encodeResourceId(resourceId)), DiagnosticSettingsCategoryImpl::new); } @Override public DiagnosticSettingsCategory getCategory(String resourceId, String name) { return new DiagnosticSettingsCategoryImpl( this.manager().serviceClient().getDiagnosticSettingsCategories().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSettingsCategory> getCategoryAsync(String resourceId, String name) { return this .manager() .serviceClient() .getDiagnosticSettingsCategories() .getAsync(ResourceUtils.encodeResourceId(resourceId), name) .map(DiagnosticSettingsCategoryImpl::new); } @Override public PagedIterable<DiagnosticSetting> listByResource(String resourceId) { return new PagedIterable<>(this.listByResourceAsync(resourceId)); } @Override public PagedFlux<DiagnosticSetting> listByResourceAsync(String resourceId) { return PagedConverter.mapPage( this .manager() .serviceClient() .getDiagnosticSettingsOperations() .listAsync(ResourceUtils.encodeResourceId(resourceId)), inner -> new DiagnosticSettingImpl(inner.name(), inner, manager)); } @Override public void delete(String resourceId, String name) { this.manager().serviceClient().getDiagnosticSettingsOperations().delete(ResourceUtils.encodeResourceId(resourceId), name); } @Override public Mono<Void> deleteAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().deleteAsync(ResourceUtils.encodeResourceId(resourceId), name); } @Override public DiagnosticSetting get(String resourceId, String name) { return wrapModel(this.manager().serviceClient().getDiagnosticSettingsOperations().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSetting> getAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(ResourceUtils.encodeResourceId(resourceId), name).map(this::wrapModel); } @Override public Mono<Void> deleteByIdAsync(String id) { return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)); } @Override @Override public Flux<String> deleteByIdsAsync(String... ids) { return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids))); } @Override public void deleteByIds(Collection<String> ids) { if (ids != null && !ids.isEmpty()) { this.deleteByIdsAsync(ids).blockLast(); } } @Override public void deleteByIds(String... ids) { this.deleteByIds(new ArrayList<>(Arrays.asList(ids))); } @Override public DiagnosticSetting getById(String id) { return wrapModel(this.inner().get(getResourceIdFromSettingsId(id), getNameFromSettingsId(id))); } @Override public Mono<DiagnosticSetting> getByIdAsync(String id) { return this.inner().getAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).map(this::wrapModel); } private String getResourceIdFromSettingsId(String diagnosticSettingId) { diagnosticSettingId = ResourceUtils.encodeResourceId(diagnosticSettingId); if (diagnosticSettingId == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Parameter 'resourceId' is required and cannot be null.")); } int dsIdx = diagnosticSettingId.lastIndexOf(DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI); if (dsIdx == -1) { throw logger.logExceptionAsError(new IllegalArgumentException( "Parameter 'resourceId' does not represent a valid Diagnostic Settings resource Id [" + diagnosticSettingId + "].")); } return diagnosticSettingId.substring(0, dsIdx); } private String getNameFromSettingsId(String diagnosticSettingId) { String resourceId = getResourceIdFromSettingsId(diagnosticSettingId); return ResourceUtils.encodeResourceId(diagnosticSettingId) .substring(resourceId.length() + DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI.length()); } }
class DiagnosticSettingsImpl extends CreatableResourcesImpl<DiagnosticSetting, DiagnosticSettingImpl, DiagnosticSettingsResourceInner> implements DiagnosticSettings { private final ClientLogger logger = new ClientLogger(getClass()); private final MonitorManager manager; public DiagnosticSettingsImpl(final MonitorManager manager) { this.manager = manager; } @Override public DiagnosticSettingImpl define(String name) { return wrapModel(name); } @Override protected DiagnosticSettingImpl wrapModel(String name) { DiagnosticSettingsResourceInner inner = new DiagnosticSettingsResourceInner(); return new DiagnosticSettingImpl(name, inner, this.manager()); } @Override protected DiagnosticSettingImpl wrapModel(DiagnosticSettingsResourceInner inner) { if (inner == null) { return null; } return new DiagnosticSettingImpl(inner.name(), inner, this.manager()); } @Override public MonitorManager manager() { return this.manager; } public DiagnosticSettingsOperationsClient inner() { return this.manager().serviceClient().getDiagnosticSettingsOperations(); } @Override public List<DiagnosticSettingsCategory> listCategoriesByResource(String resourceId) { List<DiagnosticSettingsCategory> categories = new ArrayList<>(); PagedIterable<DiagnosticSettingsCategoryResourceInner> collection = this.manager().serviceClient().getDiagnosticSettingsCategories().list(ResourceUtils.encodeResourceId(resourceId)); if (collection != null) { for (DiagnosticSettingsCategoryResourceInner category : collection) { categories.add(new DiagnosticSettingsCategoryImpl(category)); } } return categories; } @Override public PagedFlux<DiagnosticSettingsCategory> listCategoriesByResourceAsync(String resourceId) { return PagedConverter.mapPage(this .manager .serviceClient() .getDiagnosticSettingsCategories() .listAsync(ResourceUtils.encodeResourceId(resourceId)), DiagnosticSettingsCategoryImpl::new); } @Override public DiagnosticSettingsCategory getCategory(String resourceId, String name) { return new DiagnosticSettingsCategoryImpl( this.manager().serviceClient().getDiagnosticSettingsCategories().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSettingsCategory> getCategoryAsync(String resourceId, String name) { return this .manager() .serviceClient() .getDiagnosticSettingsCategories() .getAsync(ResourceUtils.encodeResourceId(resourceId), name) .map(DiagnosticSettingsCategoryImpl::new); } @Override public PagedIterable<DiagnosticSetting> listByResource(String resourceId) { return new PagedIterable<>(this.listByResourceAsync(resourceId)); } @Override public PagedFlux<DiagnosticSetting> listByResourceAsync(String resourceId) { return PagedConverter.mapPage( this .manager() .serviceClient() .getDiagnosticSettingsOperations() .listAsync(ResourceUtils.encodeResourceId(resourceId)), inner -> new DiagnosticSettingImpl(inner.name(), inner, manager)); } @Override public void delete(String resourceId, String name) { this.manager().serviceClient().getDiagnosticSettingsOperations().delete(ResourceUtils.encodeResourceId(resourceId), name); } @Override public Mono<Void> deleteAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().deleteAsync(ResourceUtils.encodeResourceId(resourceId), name); } @Override public DiagnosticSetting get(String resourceId, String name) { return wrapModel(this.manager().serviceClient().getDiagnosticSettingsOperations().get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono<DiagnosticSetting> getAsync(String resourceId, String name) { return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(ResourceUtils.encodeResourceId(resourceId), name).map(this::wrapModel); } @Override public Mono<Void> deleteByIdAsync(String id) { return this .manager() .serviceClient() .getDiagnosticSettingsOperations() .deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)); } @Override @Override public Flux<String> deleteByIdsAsync(String... ids) { return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids))); } @Override public void deleteByIds(Collection<String> ids) { if (ids != null && !ids.isEmpty()) { this.deleteByIdsAsync(ids).blockLast(); } } @Override public void deleteByIds(String... ids) { this.deleteByIds(new ArrayList<>(Arrays.asList(ids))); } @Override public DiagnosticSetting getById(String id) { return wrapModel(this.inner().get(getResourceIdFromSettingsId(id), getNameFromSettingsId(id))); } @Override public Mono<DiagnosticSetting> getByIdAsync(String id) { return this.inner().getAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).map(this::wrapModel); } /** * Get the resourceID from the diagnostic setting ID, with proper encoding. * * @param diagnosticSettingId ID of the diagnostic setting resource * @return properly encoded resourceID of the diagnostic setting */ private String getResourceIdFromSettingsId(String diagnosticSettingId) { return getResourceIdFromSettingsId(diagnosticSettingId, true); } /** * Get the resourceID from the diagnostic setting ID. * * @param diagnosticSettingId ID of the diagnostic setting resource * @param encodeResourceId whether to ensure the resourceID is properly encoded * @return resourceID of the diagnostic setting */ private String getResourceIdFromSettingsId(String diagnosticSettingId, boolean encodeResourceId) { if (diagnosticSettingId == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Parameter 'resourceId' is required and cannot be null.")); } if (encodeResourceId) { diagnosticSettingId = ResourceUtils.encodeResourceId(diagnosticSettingId); } int dsIdx = diagnosticSettingId.lastIndexOf(DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI); if (dsIdx == -1) { throw logger.logExceptionAsError(new IllegalArgumentException( "Parameter 'resourceId' does not represent a valid Diagnostic Settings resource Id [" + diagnosticSettingId + "].")); } return diagnosticSettingId.substring(0, dsIdx); } /** * Get raw diagnostic setting name from id. * * @param diagnosticSettingId ID of the diagnostic settting * @return raw name of the diagnostic setting */ private String getNameFromSettingsId(String diagnosticSettingId) { String resourceId = getResourceIdFromSettingsId(diagnosticSettingId, false); return diagnosticSettingId .substring(resourceId.length() + DiagnosticSettingImpl.DIAGNOSTIC_SETTINGS_URI.length()); } }
Map `Canceled` to `USER_CANCELLED`
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
} else {
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
Other status would be `isComplete=false`
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
this.status = LongRunningOperationStatus.fromString(status, false);
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
The test case was wrong. In the buggy version, 1st 200 with `status=Retry` is treated as complete, hence the 2nd 500 not happen at all, then it gets to the finalUrl. Hence count=2 Updated the test to - 1st, poll 200 with `status=Succeeded`; poll complete - 2nd, final 500, pipeline do retry - 3nd, final 200 --- This test case probably needs improvement. Current array based condition is too hard to understand.
static Stream<int[]> statusCodeProvider() { return Stream.of( new int[]{500, 200, 200, 3}, new int[]{200, 500, 200, 3}); }
new int[]{200, 500, 200, 3});
static Stream<int[]> statusCodeProvider() { return Stream.of( new int[]{500, 200, 200, 3}, new int[]{200, 500, 200, 3}); }
class OperationResourcePollingStrategyTest { private static final TypeReference<TestPollResult> POLL_RESULT_TYPE_REFERENCE = TypeReference.createInstance(TestPollResult.class); private static final HttpHeaderName OPERATION_LOCATION = HttpHeaderName.fromString("Operation-Location"); @Test public void operationLocationPollingStrategySucceedsOnPollWithResourceLocation() { int[] activationCallCount = new int[1]; String mockPollUrl = "http: String finalResultUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded", finalResultUrl))); } else if (finalResultUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state", finalResultUrl))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @Test public void operationLocationPollingStrategySucceedsOnPollWithPostLocationHeader() { int[] activationCallCount = new int[1]; String mockPollUrl = "http: String finalResultUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl).set(HttpHeaderName.LOCATION, finalResultUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded"))); } else if (finalResultUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last(). flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @Test public void operationLocationPollingWithPostNoLocationHeaderInPollResponse() { int[] activationCallCount = new int[1]; String mockPollUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last(). flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "Succeeded".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @Test public void operationLocationPollingStrategySucceedsOnPollWithPut() { int[] activationCallCount = new int[1]; String putUrl = "http: String mockPollUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.PUT, putUrl), 200, new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded"))); } else if (putUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @SuppressWarnings("deprecation") @ParameterizedTest @ValueSource(strings = {"Operation-Location", "resourceLocation"}) public void operationResourcePollingStrategyRelativePath(String headerName) { int[] activationCallCount = new int[1]; String endpointUrl = "http: String mockPollRelativePath = "/poll"; String finalResultAbsolutePath = endpointUrl + "/final"; String mockPollAbsolutePath = endpointUrl + mockPollRelativePath; Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(headerName, mockPollRelativePath), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollAbsolutePath); HttpClient httpClient = request -> { if (mockPollAbsolutePath.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded", finalResultAbsolutePath))); } else if (finalResultAbsolutePath.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state", finalResultAbsolutePath))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient), endpointUrl, new DefaultJsonSerializer(), headerName, Context.NONE), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @Test public void operationLocationPollingStrategyFailsOnPoll() { int[] activationCallCount = new int[1]; String mockPollUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Failed"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.FAILED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectErrorMessage("Long running operation failed.") .verify(); assertEquals(1, activationCallCount[0]); } @ParameterizedTest @MethodSource("statusCodeProvider") public void retryPollingOperationWithPostActivationOperation(int[] args) { int[] activationCallCount = new int[1]; String mockPollUrl = "http: String finalResultUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl).set(HttpHeaderName.LOCATION, finalResultUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpRequest finalRequest = new HttpRequest(HttpMethod.GET, finalResultUrl); AtomicInteger attemptCount = new AtomicInteger(); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(new RetryPolicy()) .httpClient(request -> { int count = attemptCount.getAndIncrement(); if (mockPollUrl.equals(request.getUrl().toString()) && count == 0) { return Mono.just(new MockHttpResponse(pollRequest, args[0], new HttpHeaders().set(HttpHeaderName.LOCATION, finalResultUrl), new TestPollResult("Succeeded"))); } else if (mockPollUrl.equals(request.getUrl().toString()) && count == 1) { return Mono.just(new MockHttpResponse(pollRequest, args[1], new HttpHeaders().set(HttpHeaderName.LOCATION, finalResultUrl), new TestPollResult("Succeeded"))); } else if (finalResultUrl.equals(request.getUrl().toString()) && count == 1) { return Mono.just(new MockHttpResponse(finalRequest, args[1], new HttpHeaders(), new TestPollResult("final-state"))); } else if (finalResultUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(finalRequest, args[2], new HttpHeaders(), new TestPollResult("final-state"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }) .build(); PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(pipeline), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(args[3], attemptCount.get()); assertEquals(1, activationCallCount[0]); } @ParameterizedTest @CsvSource({ "http: "http: public void operationLocationPollingStrategyServiceVersionTest(String requestPollUrl, String responsePollUrl, String requestFinalResultUrl, String responseFinalResultUrl) { int[] activationCallCount = new int[1]; Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, responsePollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, requestPollUrl); HttpClient httpClient = request -> { if (requestPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded", responseFinalResultUrl))); } else if (requestFinalResultUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state", responseFinalResultUrl))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollingStrategyOptions pollingStrategyOptions = new PollingStrategyOptions(createPipeline(httpClient)) .setServiceVersion("2023-03-22"); PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(null, pollingStrategyOptions), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } }
class OperationResourcePollingStrategyTest { private static final TypeReference<TestPollResult> POLL_RESULT_TYPE_REFERENCE = TypeReference.createInstance(TestPollResult.class); private static final HttpHeaderName OPERATION_LOCATION = HttpHeaderName.fromString("Operation-Location"); @Test public void operationLocationPollingStrategySucceedsOnPollWithResourceLocation() { int[] activationCallCount = new int[1]; String mockPollUrl = "http: String finalResultUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded", finalResultUrl))); } else if (finalResultUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state", finalResultUrl))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @Test public void operationLocationPollingStrategySucceedsOnPollWithPostLocationHeader() { int[] activationCallCount = new int[1]; String mockPollUrl = "http: String finalResultUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl).set(HttpHeaderName.LOCATION, finalResultUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded"))); } else if (finalResultUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last(). flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @Test public void operationLocationPollingWithPostNoLocationHeaderInPollResponse() { int[] activationCallCount = new int[1]; String mockPollUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last(). flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "Succeeded".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @Test public void operationLocationPollingStrategySucceedsOnPollWithPut() { int[] activationCallCount = new int[1]; String putUrl = "http: String mockPollUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.PUT, putUrl), 200, new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded"))); } else if (putUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @SuppressWarnings("deprecation") @ParameterizedTest @ValueSource(strings = {"Operation-Location", "resourceLocation"}) public void operationResourcePollingStrategyRelativePath(String headerName) { int[] activationCallCount = new int[1]; String endpointUrl = "http: String mockPollRelativePath = "/poll"; String finalResultAbsolutePath = endpointUrl + "/final"; String mockPollAbsolutePath = endpointUrl + mockPollRelativePath; Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(headerName, mockPollRelativePath), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollAbsolutePath); HttpClient httpClient = request -> { if (mockPollAbsolutePath.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded", finalResultAbsolutePath))); } else if (finalResultAbsolutePath.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state", finalResultAbsolutePath))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient), endpointUrl, new DefaultJsonSerializer(), headerName, Context.NONE), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } @Test public void operationLocationPollingStrategyFailsOnPoll() { int[] activationCallCount = new int[1]; String mockPollUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpClient httpClient = request -> { if (mockPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Failed"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(createPipeline(httpClient)), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.FAILED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectErrorMessage("Long running operation failed.") .verify(); assertEquals(1, activationCallCount[0]); } @ParameterizedTest @MethodSource("statusCodeProvider") public void retryPollingOperationWithPostActivationOperation(int[] args) { int[] activationCallCount = new int[1]; String mockPollUrl = "http: String finalResultUrl = "http: Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, mockPollUrl).set(HttpHeaderName.LOCATION, finalResultUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, mockPollUrl); HttpRequest finalRequest = new HttpRequest(HttpMethod.GET, finalResultUrl); AtomicInteger attemptCount = new AtomicInteger(); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(new RetryPolicy()) .httpClient(request -> { int count = attemptCount.getAndIncrement(); if (mockPollUrl.equals(request.getUrl().toString()) && count == 0) { return Mono.just(new MockHttpResponse(pollRequest, args[0], new HttpHeaders().set(HttpHeaderName.LOCATION, finalResultUrl), new TestPollResult("Succeeded"))); } else if (mockPollUrl.equals(request.getUrl().toString()) && count == 1) { return Mono.just(new MockHttpResponse(pollRequest, args[1], new HttpHeaders().set(HttpHeaderName.LOCATION, finalResultUrl), new TestPollResult("Succeeded"))); } else if (finalResultUrl.equals(request.getUrl().toString()) && count == 1) { return Mono.just(new MockHttpResponse(finalRequest, args[1], new HttpHeaders(), new TestPollResult("final-state"))); } else if (finalResultUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(finalRequest, args[2], new HttpHeaders(), new TestPollResult("final-state"))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }) .build(); PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(pipeline), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(args[3], attemptCount.get()); assertEquals(1, activationCallCount[0]); } @ParameterizedTest @CsvSource({ "http: "http: public void operationLocationPollingStrategyServiceVersionTest(String requestPollUrl, String responsePollUrl, String requestFinalResultUrl, String responseFinalResultUrl) { int[] activationCallCount = new int[1]; Supplier<Mono<Response<TestPollResult>>> activationOperation = () -> Mono.fromCallable(() -> { activationCallCount[0]++; return new SimpleResponse<>(new HttpRequest(HttpMethod.POST, "http: new HttpHeaders().set(OPERATION_LOCATION, responsePollUrl), new TestPollResult("InProgress")); }); HttpRequest pollRequest = new HttpRequest(HttpMethod.GET, requestPollUrl); HttpClient httpClient = request -> { if (requestPollUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("Succeeded", responseFinalResultUrl))); } else if (requestFinalResultUrl.equals(request.getUrl().toString())) { return Mono.just(new MockHttpResponse(pollRequest, 200, new HttpHeaders(), new TestPollResult("final-state", responseFinalResultUrl))); } else { return Mono.error(new IllegalArgumentException("Unknown request URL " + request.getUrl())); } }; PollingStrategyOptions pollingStrategyOptions = new PollingStrategyOptions(createPipeline(httpClient)) .setServiceVersion("2023-03-22"); PollerFlux<TestPollResult, TestPollResult> pollerFlux = PollerFlux.create(Duration.ofMillis(1), activationOperation::get, new OperationResourcePollingStrategy<>(null, pollingStrategyOptions), POLL_RESULT_TYPE_REFERENCE, POLL_RESULT_TYPE_REFERENCE); StepVerifier.create(pollerFlux) .expectSubscription() .expectNextMatches(asyncPollResponse -> asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .verifyComplete(); StepVerifier.create(pollerFlux.takeUntil(apr -> apr.getStatus().isComplete()) .last() .flatMap(AsyncPollResponse::getFinalResult)) .expectNextMatches(testPollResult -> "final-state".equals(testPollResult.getStatus())) .verifyComplete(); assertEquals(1, activationCallCount[0]); } }
This is a behavior breaking change but it's the right change to make as we should terminate the poller on only known terminal states. Should we consider introducing a compat switch here? cc: @JonathanGiles
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
this.status = LongRunningOperationStatus.fromString(status, false);
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
I have another string to add here. "status\":\"notRunning\" [ForkJoinPool-1-worker-5] INFO - {"az.sdk.message":"HTTP response","contentLength":"88","statusCode":200,"url":"REDACTED","durationMs":315,"Content-Length":"88","Content-Type":"application/json","retry-after":"6","x-ms-request-id":"REDACTED","x-envoy-upstream-service-time":"REDACTED","OpenAI-Processing-Ms":"REDACTED","x-ms-client-request-id":"e7de899a-dd5a-478f-9243-b29136b2b3e4","apim-request-id":"REDACTED","Strict-Transport-Security":"REDACTED","x-content-type-options":"REDACTED","x-ms-region":"REDACTED","Date":"Fri, 14 Jul 2023 15:37:24 GMT","body":"{\"created\":1689349043,\"id\":\"1bc96f44-1fa6-4ee4-980e-422195dd7fa1\",**\"status\":\"notRunning\"**}"}
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
this.status = LongRunningOperationStatus.fromString(status, false);
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
@mssfang I guess it is OpenAI? That is where we find the problem of LRO poll not working properly, and hence this fix ("notRunning" be an *unknown* status, not a complete status, hence should continue polling).
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
this.status = LongRunningOperationStatus.fromString(status, false);
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
Yes. It is from OpenAI LRO. Thanks @weidongxu-microsoft.
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
this.status = LongRunningOperationStatus.fromString(status, false);
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
Got you. I was trying to merge for last month, but the behavior change has certain impact and Srikanta recommend Jonathan to review as well. I will try to get it in this month. --- But I don't know why async in openai worked... That should be the same logic (just Reactor vs. line by line). The agrifood test uses async client. They got the same problem that "status=Waiting" get LRO completed.
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
this.status = LongRunningOperationStatus.fromString(status, false);
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
If we were to have a compat switch, I'd like to also have a plan for how long it would hang around before we removed it, and also that we held the switch close to our chest so that it does not needlessly become relied upon.
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
this.status = LongRunningOperationStatus.fromString(status, false);
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
Spoke to @JonathanGiles offline and decided not have the compact switch as this is not an issue for most services and OpenAI (where we found this issue) will not have LROs for image generation.
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
this.status = LongRunningOperationStatus.fromString(status, false);
public PollResult setStatus(String status) { if (PollingConstants.STATUS_NOT_STARTED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.NOT_STARTED; } else if (PollingConstants.STATUS_IN_PROGRESS.equalsIgnoreCase(status) || PollingConstants.STATUS_RUNNING.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.IN_PROGRESS; } else if (PollingConstants.STATUS_SUCCEEDED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } else if (PollingConstants.STATUS_FAILED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.FAILED; } else if (PollingConstants.STATUS_CANCELLED.equalsIgnoreCase(status)) { this.status = LongRunningOperationStatus.USER_CANCELLED; } else { this.status = LongRunningOperationStatus.fromString(status, false); } return this; }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
class PollResult { private LongRunningOperationStatus status; private String resourceLocation; /** * Gets the status of the long-running operation. * * @return the status represented as a {@link LongRunningOperationStatus} */ public LongRunningOperationStatus getStatus() { return status; } /** * Sets the long-running operation status in the format of a string returned by the service. This is called by * the deserializer when a response is received. * * @param status the status of the long-running operation * @return the modified PollResult instance */ @JsonSetter /** * Sets the long-running operation status in the format of the {@link LongRunningOperationStatus} enum. * * @param status the status of the long-running operation * @return the modified PollResult instance */ public PollResult setStatus(LongRunningOperationStatus status) { this.status = status; return this; } /** * Gets the resource location URL to get the final result. This is often available in the response when the * long-running operation has been successfully completed. * * @return the resource location URL to get the final result */ public String getResourceLocation() { return resourceLocation; } /** * Sets the resource location URL. this should only be called by the deserializer when a response is received. * * @param resourceLocation the resource location URL * @return the modified PollResult instance */ public PollResult setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } }
You should add unit tests and note why to add this logic here.
private static String getVersion() { String version = "unknown"; try { Properties properties = PropertiesLoaderUtils.loadProperties( new ClassPathResource("azure-spring-identifier.properties")); version = properties.getProperty("version"); if (version.contains("beta")) { version = version.replace("beta", "b"); } } catch (IOException e) { LOGGER.warn("Can not get version."); } return version; }
if (version.contains("beta")) {
private static String getVersion() { String version = "unknown"; try { Properties properties = PropertiesLoaderUtils.loadProperties( new ClassPathResource("azure-spring-identifier.properties")); version = properties.getProperty("version"); version = formatVersion(version); } catch (IOException e) { LOGGER.warn("Can not get version."); } return version; }
class AzureSpringIdentifier { private AzureSpringIdentifier() { } private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringIdentifier.class); public static final String VERSION = getVersion(); public static final String AZURE_SPRING_APP_CONFIG = "az-sp-cfg/" + VERSION; public static final String AZURE_SPRING_EVENT_HUBS = "az-sp-eh/" + VERSION; public static final String AZURE_SPRING_EVENT_GRID = "az-sp-eg/" + VERSION; public static final String AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH = ".az-sp-kafka"; public static final String AZURE_SPRING_KEY_VAULT_SECRETS = "az-sp-kv/" + VERSION; public static final String AZURE_SPRING_KEY_VAULT_CERTIFICATES = "az-sp-kv-ct/" + VERSION; public static final String AZURE_SPRING_MYSQL_OAUTH = "az-sp-mysql/" + VERSION; public static final String AZURE_SPRING_POSTGRESQL_OAUTH = "az-sp-psql/" + VERSION; /** * Azure Spring ServiceBus */ public static final String AZURE_SPRING_SERVICE_BUS = "az-sp-bus/" + VERSION; public static final String AZURE_SPRING_PASSWORDLESS_SERVICE_BUS = "az-sp-pl-sb/" + VERSION; /** * Azure Spring Storage Blob */ public static final String AZURE_SPRING_STORAGE_BLOB = "az-sp-sb/" + VERSION; /** * Azure Spring Storage Files */ public static final String AZURE_SPRING_STORAGE_FILES = "az-sp-sf/" + VERSION; public static final String AZURE_SPRING_COSMOS = "az-sp-cos/" + VERSION; public static final String AZURE_SPRING_STORAGE_QUEUE = "az-sp-sq/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_STORAGE_QUEUE = "az-si-sq/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_SERVICE_BUS = "az-si-sb/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_EVENT_HUBS = "az-si-eh/" + VERSION; /** * AZURE_SPRING_AAD does not contain VERSION, because AAD server support 2 headers: 1. x-client-SKU; 2. * x-client-VER; */ public static final String AZURE_SPRING_AAD = "az-sp-aad"; /** * Azure Spring B2C */ public static final String AZURE_SPRING_B2C = "az-sp-b2c"; public static final String AZURE_SPRING_IDENTITY = "az-sp-id/" + VERSION; }
class AzureSpringIdentifier { private AzureSpringIdentifier() { } private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringIdentifier.class); public static final String VERSION = getVersion(); public static final int MAX_VERSION_LENGTH = 12; public static final String AZURE_SPRING_APP_CONFIG = "az-sp-cfg/" + VERSION; public static final String AZURE_SPRING_EVENT_HUBS = "az-sp-eh/" + VERSION; public static final String AZURE_SPRING_EVENT_GRID = "az-sp-eg/" + VERSION; public static final String AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH = ".az-sp-kafka"; public static final String AZURE_SPRING_KEY_VAULT_SECRETS = "az-sp-kv/" + VERSION; public static final String AZURE_SPRING_KEY_VAULT_CERTIFICATES = "az-sp-kv-ct/" + VERSION; public static final String AZURE_SPRING_MYSQL_OAUTH = "az-sp-mysql/" + VERSION; public static final String AZURE_SPRING_POSTGRESQL_OAUTH = "az-sp-psql/" + VERSION; /** * Azure Spring ServiceBus */ public static final String AZURE_SPRING_SERVICE_BUS = "az-sp-bus/" + VERSION; public static final String AZURE_SPRING_PASSWORDLESS_SERVICE_BUS = "az-sp-pl-sb/" + VERSION; /** * Azure Spring Storage Blob */ public static final String AZURE_SPRING_STORAGE_BLOB = "az-sp-sb/" + VERSION; /** * Azure Spring Storage Files */ public static final String AZURE_SPRING_STORAGE_FILES = "az-sp-sf/" + VERSION; public static final String AZURE_SPRING_COSMOS = "az-sp-cos/" + VERSION; public static final String AZURE_SPRING_STORAGE_QUEUE = "az-sp-sq/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_STORAGE_QUEUE = "az-si-sq/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_SERVICE_BUS = "az-si-sb/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_EVENT_HUBS = "az-si-eh/" + VERSION; /** * AZURE_SPRING_AAD does not contain VERSION, because AAD server support 2 headers: 1. x-client-SKU; 2. * x-client-VER; */ public static final String AZURE_SPRING_AAD = "az-sp-aad"; /** * Azure Spring B2C */ public static final String AZURE_SPRING_B2C = "az-sp-b2c"; public static final String AZURE_SPRING_IDENTITY = "az-sp-id/" + VERSION; static String formatVersion(String version) { if (version.length() > MAX_VERSION_LENGTH) { if (version.contains("beta")) { version = version.replace("beta", "b"); } else if (version.contains("alpha")) { version = version.replace("alpha", "a"); } else { throw new RuntimeException("version is too long to create application id"); } } return version; } }
I would recommend that we add a logic here, to define the max size a version could reach. And if a version length exceeds that MAX, and the version contains "beta" or "alpha", we then replace the "beta" with "b", and "alpha" with "a".
private static String getVersion() { String version = "unknown"; try { Properties properties = PropertiesLoaderUtils.loadProperties( new ClassPathResource("azure-spring-identifier.properties")); version = properties.getProperty("version"); if (version.contains("beta")) { version = version.replace("beta", "b"); } } catch (IOException e) { LOGGER.warn("Can not get version."); } return version; }
if (version.contains("beta")) {
private static String getVersion() { String version = "unknown"; try { Properties properties = PropertiesLoaderUtils.loadProperties( new ClassPathResource("azure-spring-identifier.properties")); version = properties.getProperty("version"); version = formatVersion(version); } catch (IOException e) { LOGGER.warn("Can not get version."); } return version; }
class AzureSpringIdentifier { private AzureSpringIdentifier() { } private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringIdentifier.class); public static final String VERSION = getVersion(); public static final String AZURE_SPRING_APP_CONFIG = "az-sp-cfg/" + VERSION; public static final String AZURE_SPRING_EVENT_HUBS = "az-sp-eh/" + VERSION; public static final String AZURE_SPRING_EVENT_GRID = "az-sp-eg/" + VERSION; public static final String AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH = ".az-sp-kafka"; public static final String AZURE_SPRING_KEY_VAULT_SECRETS = "az-sp-kv/" + VERSION; public static final String AZURE_SPRING_KEY_VAULT_CERTIFICATES = "az-sp-kv-ct/" + VERSION; public static final String AZURE_SPRING_MYSQL_OAUTH = "az-sp-mysql/" + VERSION; public static final String AZURE_SPRING_POSTGRESQL_OAUTH = "az-sp-psql/" + VERSION; /** * Azure Spring ServiceBus */ public static final String AZURE_SPRING_SERVICE_BUS = "az-sp-bus/" + VERSION; public static final String AZURE_SPRING_PASSWORDLESS_SERVICE_BUS = "az-sp-pl-sb/" + VERSION; /** * Azure Spring Storage Blob */ public static final String AZURE_SPRING_STORAGE_BLOB = "az-sp-sb/" + VERSION; /** * Azure Spring Storage Files */ public static final String AZURE_SPRING_STORAGE_FILES = "az-sp-sf/" + VERSION; public static final String AZURE_SPRING_COSMOS = "az-sp-cos/" + VERSION; public static final String AZURE_SPRING_STORAGE_QUEUE = "az-sp-sq/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_STORAGE_QUEUE = "az-si-sq/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_SERVICE_BUS = "az-si-sb/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_EVENT_HUBS = "az-si-eh/" + VERSION; /** * AZURE_SPRING_AAD does not contain VERSION, because AAD server support 2 headers: 1. x-client-SKU; 2. * x-client-VER; */ public static final String AZURE_SPRING_AAD = "az-sp-aad"; /** * Azure Spring B2C */ public static final String AZURE_SPRING_B2C = "az-sp-b2c"; public static final String AZURE_SPRING_IDENTITY = "az-sp-id/" + VERSION; }
class AzureSpringIdentifier { private AzureSpringIdentifier() { } private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringIdentifier.class); public static final String VERSION = getVersion(); public static final int MAX_VERSION_LENGTH = 12; public static final String AZURE_SPRING_APP_CONFIG = "az-sp-cfg/" + VERSION; public static final String AZURE_SPRING_EVENT_HUBS = "az-sp-eh/" + VERSION; public static final String AZURE_SPRING_EVENT_GRID = "az-sp-eg/" + VERSION; public static final String AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH = ".az-sp-kafka"; public static final String AZURE_SPRING_KEY_VAULT_SECRETS = "az-sp-kv/" + VERSION; public static final String AZURE_SPRING_KEY_VAULT_CERTIFICATES = "az-sp-kv-ct/" + VERSION; public static final String AZURE_SPRING_MYSQL_OAUTH = "az-sp-mysql/" + VERSION; public static final String AZURE_SPRING_POSTGRESQL_OAUTH = "az-sp-psql/" + VERSION; /** * Azure Spring ServiceBus */ public static final String AZURE_SPRING_SERVICE_BUS = "az-sp-bus/" + VERSION; public static final String AZURE_SPRING_PASSWORDLESS_SERVICE_BUS = "az-sp-pl-sb/" + VERSION; /** * Azure Spring Storage Blob */ public static final String AZURE_SPRING_STORAGE_BLOB = "az-sp-sb/" + VERSION; /** * Azure Spring Storage Files */ public static final String AZURE_SPRING_STORAGE_FILES = "az-sp-sf/" + VERSION; public static final String AZURE_SPRING_COSMOS = "az-sp-cos/" + VERSION; public static final String AZURE_SPRING_STORAGE_QUEUE = "az-sp-sq/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_STORAGE_QUEUE = "az-si-sq/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_SERVICE_BUS = "az-si-sb/" + VERSION; public static final String AZURE_SPRING_INTEGRATION_EVENT_HUBS = "az-si-eh/" + VERSION; /** * AZURE_SPRING_AAD does not contain VERSION, because AAD server support 2 headers: 1. x-client-SKU; 2. * x-client-VER; */ public static final String AZURE_SPRING_AAD = "az-sp-aad"; /** * Azure Spring B2C */ public static final String AZURE_SPRING_B2C = "az-sp-b2c"; public static final String AZURE_SPRING_IDENTITY = "az-sp-id/" + VERSION; static String formatVersion(String version) { if (version.length() > MAX_VERSION_LENGTH) { if (version.contains("beta")) { version = version.replace("beta", "b"); } else if (version.contains("alpha")) { version = version.replace("alpha", "a"); } else { throw new RuntimeException("version is too long to create application id"); } } return version; } }
let's use BatchLogRecordProcessor
private void initOTelLogger(LogRecordExporter logRecordExporter) { if (azureMonitorExporterBuilderOpt.isPresent()) { SdkLoggerProvider loggerProvider = SdkLoggerProvider.builder() .addLogRecordProcessor(SimpleLogRecordProcessor.create(logRecordExporter)) .build(); GlobalLoggerProvider.set(loggerProvider); } }
.addLogRecordProcessor(SimpleLogRecordProcessor.create(logRecordExporter))
private void initOTelLogger(LogRecordExporter logRecordExporter) { if (azureMonitorExporterBuilderOpt.isPresent()) { BatchLogRecordProcessor batchLogRecordProcessor = BatchLogRecordProcessor.builder(logRecordExporter).build(); SdkLoggerProvider loggerProvider = SdkLoggerProvider.builder() .addLogRecordProcessor(batchLogRecordProcessor) .build(); GlobalLoggerProvider.set(loggerProvider); } }
class AzureTelemetryConfig { private static final ClientLogger LOGGER = new ClientLogger(AzureTelemetryConfig.class); private static final String CONNECTION_STRING_ERROR_MESSAGE = "Unable to find the Application Insights connection string."; private final Optional<AzureMonitorExporterBuilder> azureMonitorExporterBuilderOpt; public AzureTelemetryConfig(@Value("${applicationinsights.connection.string:}") String connectionStringSysProp, AzureTelemetryActivation azureTelemetryActivation, ObjectProvider<HttpPipeline> httpPipeline) { if (azureTelemetryActivation.isTrue()) { this.azureMonitorExporterBuilderOpt = createAzureMonitorExporterBuilder(connectionStringSysProp, httpPipeline); } else { LOGGER.info("Application Insights for Spring native is disabled for a non-native image runtime environment. We recommend using the Application Insights Java agent."); azureMonitorExporterBuilderOpt = Optional.empty(); } } private Optional<AzureMonitorExporterBuilder> createAzureMonitorExporterBuilder(String connectionStringSysProp, ObjectProvider<HttpPipeline> httpPipeline) { Optional<String> connectionString = ConnectionStringRetriever.retrieveConnectionString(connectionStringSysProp); if (connectionString.isPresent()) { try { AzureMonitorExporterBuilder azureMonitorExporterBuilder = new AzureMonitorExporterBuilder().connectionString(connectionString.get()); HttpPipeline providedHttpPipeline = httpPipeline.getIfAvailable(); if (providedHttpPipeline != null) { azureMonitorExporterBuilder = azureMonitorExporterBuilder.httpPipeline(providedHttpPipeline); } return Optional.of(azureMonitorExporterBuilder); } catch (IllegalArgumentException illegalArgumentException) { String errorMessage = illegalArgumentException.getMessage(); if (errorMessage.contains("InstrumentationKey")) { LOGGER.warning(CONNECTION_STRING_ERROR_MESSAGE + " Please check you have not used an instrumentation key instead of a connection string"); } } } else { LOGGER.warning(CONNECTION_STRING_ERROR_MESSAGE); } return Optional.empty(); } @Bean public MetricExporter metricExporter() { if (!azureMonitorExporterBuilderOpt.isPresent()) { return null; } return azureMonitorExporterBuilderOpt.get().buildMetricExporter(); } @Bean public SpanExporter spanExporter() { if (!azureMonitorExporterBuilderOpt.isPresent()) { return null; } return azureMonitorExporterBuilderOpt.get().buildTraceExporter(); } @Bean public LogRecordExporter logRecordExporter() { if (!azureMonitorExporterBuilderOpt.isPresent()) { return null; } LogRecordExporter logRecordExporter = azureMonitorExporterBuilderOpt.get().buildLogRecordExporter(); initOTelLogger(logRecordExporter); return logRecordExporter; } @Bean public OtelGlobalRegistrationPostProcessor otelGlobalRegistrationPostProcessor(AzureTelemetryActivation azureTelemetryActivation) { return new OtelGlobalRegistrationPostProcessor(azureTelemetryActivation); } }
class AzureTelemetryConfig { private static final ClientLogger LOGGER = new ClientLogger(AzureTelemetryConfig.class); private static final String CONNECTION_STRING_ERROR_MESSAGE = "Unable to find the Application Insights connection string."; private final Optional<AzureMonitorExporterBuilder> azureMonitorExporterBuilderOpt; public AzureTelemetryConfig(@Value("${applicationinsights.connection.string:}") String connectionStringSysProp, AzureTelemetryActivation azureTelemetryActivation, ObjectProvider<HttpPipeline> httpPipeline) { if (azureTelemetryActivation.isTrue()) { this.azureMonitorExporterBuilderOpt = createAzureMonitorExporterBuilder(connectionStringSysProp, httpPipeline); if (!isNativeRuntimeExecution()) { LOGGER.warning("You are using Application Insights for Spring in a non-native GraalVM runtime environment. We recommend using the Application Insights Java agent."); } } else { azureMonitorExporterBuilderOpt = Optional.empty(); } } private static boolean isNativeRuntimeExecution() { String imageCode = System.getProperty("org.graalvm.nativeimage.imagecode"); return imageCode != null; } private Optional<AzureMonitorExporterBuilder> createAzureMonitorExporterBuilder(String connectionStringSysProp, ObjectProvider<HttpPipeline> httpPipeline) { Optional<String> connectionString = ConnectionStringRetriever.retrieveConnectionString(connectionStringSysProp); if (connectionString.isPresent()) { try { AzureMonitorExporterBuilder azureMonitorExporterBuilder = new AzureMonitorExporterBuilder().connectionString(connectionString.get()); HttpPipeline providedHttpPipeline = httpPipeline.getIfAvailable(); if (providedHttpPipeline != null) { azureMonitorExporterBuilder = azureMonitorExporterBuilder.httpPipeline(providedHttpPipeline); } return Optional.of(azureMonitorExporterBuilder); } catch (IllegalArgumentException illegalArgumentException) { String errorMessage = illegalArgumentException.getMessage(); if (errorMessage.contains("InstrumentationKey")) { LOGGER.warning(CONNECTION_STRING_ERROR_MESSAGE + " Please check you have not used an instrumentation key instead of a connection string"); } } } else { LOGGER.warning(CONNECTION_STRING_ERROR_MESSAGE); } return Optional.empty(); } @Bean public MetricExporter metricExporter() { if (!azureMonitorExporterBuilderOpt.isPresent()) { return null; } return azureMonitorExporterBuilderOpt.get().buildMetricExporter(); } @Bean public SpanExporter spanExporter() { if (!azureMonitorExporterBuilderOpt.isPresent()) { return null; } return azureMonitorExporterBuilderOpt.get().buildTraceExporter(); } @Bean public LogRecordExporter logRecordExporter() { if (!azureMonitorExporterBuilderOpt.isPresent()) { return null; } LogRecordExporter logRecordExporter = azureMonitorExporterBuilderOpt.get().buildLogRecordExporter(); initOTelLogger(logRecordExporter); return logRecordExporter; } @Bean public OtelGlobalRegistrationPostProcessor otelGlobalRegistrationPostProcessor(AzureTelemetryActivation azureTelemetryActivation) { return new OtelGlobalRegistrationPostProcessor(azureTelemetryActivation); } }
i'm not sure about special casing here for connection string only, at least let's add comment to explain/justify the special case
static Optional<String> retrieveConnectionString(String connectionStringSysProp) { if (connectionStringSysProp != null) { if (connectionStringSysProp.isEmpty()) { return Optional.empty(); } String connectionStringWithoutDoubleQuotes = connectionStringSysProp.replaceAll("\"", ""); return Optional.of(connectionStringWithoutDoubleQuotes); } String connectionStringFromEnvVar = getEnvVar(APPLICATIONINSIGHTS_CONNECTION_STRING_ENV); if (connectionStringFromEnvVar != null) { return Optional.of(connectionStringFromEnvVar); } return Optional.empty(); }
String connectionStringWithoutDoubleQuotes = connectionStringSysProp.replaceAll("\"", "");
static Optional<String> retrieveConnectionString(String connectionStringSysProp) { if (connectionStringSysProp != null) { if (connectionStringSysProp.isEmpty()) { return Optional.empty(); } return Optional.of(connectionStringSysProp); } String connectionStringFromEnvVar = getEnvVar(APPLICATIONINSIGHTS_CONNECTION_STRING_ENV); if (connectionStringFromEnvVar != null) { return Optional.of(connectionStringFromEnvVar); } return Optional.empty(); }
class ConnectionStringRetriever { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING_ENV = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private ConnectionStringRetriever() { } private static String getEnvVar(String name) { return Strings.trimAndEmptyToNull(System.getenv(name)); } }
class ConnectionStringRetriever { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING_ENV = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private ConnectionStringRetriever() { } private static String getEnvVar(String name) { return Strings.trimAndEmptyToNull(System.getenv(name)); } }
can you move this upstream?
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (azureTelemetryActivation.isTrue() && bean instanceof OpenTelemetry) { OpenTelemetry openTelemetry = (OpenTelemetry) bean; GlobalOpenTelemetry.set(openTelemetry); } return bean; }
GlobalOpenTelemetry.set(openTelemetry);
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (azureTelemetryActivation.isTrue() && bean instanceof OpenTelemetry) { OpenTelemetry openTelemetry = (OpenTelemetry) bean; GlobalOpenTelemetry.set(openTelemetry); } return bean; }
class OtelGlobalRegistrationPostProcessor implements BeanPostProcessor, Ordered { private final AzureTelemetryActivation azureTelemetryActivation; public OtelGlobalRegistrationPostProcessor(AzureTelemetryActivation azureTelemetryActivation) { this.azureTelemetryActivation = azureTelemetryActivation; } @Override @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 1; } }
class OtelGlobalRegistrationPostProcessor implements BeanPostProcessor, Ordered { private final AzureTelemetryActivation azureTelemetryActivation; public OtelGlobalRegistrationPostProcessor(AzureTelemetryActivation azureTelemetryActivation) { this.azureTelemetryActivation = azureTelemetryActivation; } @Override @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 1; } }
#35722 created
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (azureTelemetryActivation.isTrue() && bean instanceof OpenTelemetry) { OpenTelemetry openTelemetry = (OpenTelemetry) bean; GlobalOpenTelemetry.set(openTelemetry); } return bean; }
GlobalOpenTelemetry.set(openTelemetry);
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (azureTelemetryActivation.isTrue() && bean instanceof OpenTelemetry) { OpenTelemetry openTelemetry = (OpenTelemetry) bean; GlobalOpenTelemetry.set(openTelemetry); } return bean; }
class OtelGlobalRegistrationPostProcessor implements BeanPostProcessor, Ordered { private final AzureTelemetryActivation azureTelemetryActivation; public OtelGlobalRegistrationPostProcessor(AzureTelemetryActivation azureTelemetryActivation) { this.azureTelemetryActivation = azureTelemetryActivation; } @Override @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 1; } }
class OtelGlobalRegistrationPostProcessor implements BeanPostProcessor, Ordered { private final AzureTelemetryActivation azureTelemetryActivation; public OtelGlobalRegistrationPostProcessor(AzureTelemetryActivation azureTelemetryActivation) { this.azureTelemetryActivation = azureTelemetryActivation; } @Override @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 1; } }
why aren't we using `interceptorManager` directly?
static String getIsolatedSigningKeyBase64() { return TEST_MODE == TestMode.PLAYBACK ? readResource("isolatedSigningKey") : Configuration.getGlobalConfiguration().get("isolatedSigningKey"); }
return TEST_MODE == TestMode.PLAYBACK
static String getIsolatedSigningKeyBase64() { return TEST_MODE == TestMode.PLAYBACK ? readResource("isolatedSigningKey") : Configuration.getGlobalConfiguration().get("isolatedSigningKey"); }
class AttestationClientTestBase extends TestProxyTestBase { protected static final SerializerAdapter ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); protected static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; protected static final ClientLogger LOGGER = new ClientLogger(AttestationClientTestBase.class); protected Tracer tracer; @Override protected void beforeTest() { super.beforeTest(); if (interceptorManager.isPlaybackMode()) { interceptorManager.addMatchers(Collections.singletonList(new CustomMatcher() .setHeadersKeyOnlyMatch(Collections.singletonList("Authorization")))); } } private static final TestMode TEST_MODE = getTestModeLocal(); static TestMode getTestModeLocal() { final String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); if (azureTestMode != null) { try { return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); } catch (IllegalArgumentException e) { LOGGER.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); return TestMode.PLAYBACK; } } LOGGER.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); return TestMode.PLAYBACK; } enum ClientTypes { SHARED, ISOLATED, AAD, } @BeforeAll public static void beforeAll() { TestBase.setupClass(); } @Override @BeforeEach public void setupTest(TestInfo testInfo) { GlobalOpenTelemetry.resetForTest(); super.setupTest(testInfo); String testMethod = testInfo.getTestMethod().isPresent() ? testInfo.getTestMethod().get().getName() : testInfo.getDisplayName(); tracer = configureLoggingExporter(testMethod); } @Override @AfterEach public void teardownTest(TestInfo testInfo) { GlobalOpenTelemetry.resetForTest(); super.teardownTest(testInfo); } @SuppressWarnings({"deprecation", "resource"}) public static Tracer configureLoggingExporter(String testName) { SdkTracerProvider tracerProvider = SdkTracerProvider.builder() .addSpanProcessor(SimpleSpanProcessor.create(new LoggingSpanExporter())) .build(); return OpenTelemetrySdk.builder() .setTracerProvider(tracerProvider) .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())) .buildAndRegisterGlobal() .getTracer(testName); } /** * Determine the Attestation instance type based on the client URI provided. * * @param clientUri - URI for the attestation client. * @return the ClientTypes corresponding to the specified client URI. */ static ClientTypes classifyClient(String clientUri) { assertNotNull(clientUri); String regionShortName = getLocationShortName(); String sharedUri = "https: if (sharedUri.equals(clientUri)) { return ClientTypes.SHARED; } else if (getIsolatedUrl().equals(clientUri)) { return ClientTypes.ISOLATED; } else if (getAadUrl().equals(clientUri)) { return ClientTypes.AAD; } throw new IllegalArgumentException(); } /** * Retrieve an authenticated attestationClientBuilder for the specified HTTP client and client URI * * @param httpClient - HTTP client ot be used for the attestation client. * @param clientUri - Client base URI to access the service. * @return Returns an attestation client builder corresponding to the httpClient and clientUri. */ AttestationClientBuilder getAuthenticatedAttestationBuilder(HttpClient httpClient, String clientUri) { AttestationClientBuilder builder = getAttestationBuilder(httpClient, clientUri); if (!interceptorManager.isPlaybackMode()) { builder.credential(new ClientSecretCredentialBuilder() .clientSecret(Configuration.getGlobalConfiguration().get("ATTESTATION_CLIENT_SECRET")) .clientId(Configuration.getGlobalConfiguration().get("ATTESTATION_CLIENT_ID")) .tenantId(Configuration.getGlobalConfiguration().get("ATTESTATION_TENANT_ID")) .httpClient(httpClient).build()); } else { builder.credential(new MockTokenCredential()); } return builder; } /** * Retrieve an attestationClientBuilder for the specified HTTP client and client URI * * @param httpClient - HTTP client ot be used for the attestation client. * @param clientUri - Client base URI to access the service. * @return Returns an attestation client builder corresponding to the httpClient and clientUri. */ AttestationClientBuilder getAttestationBuilder(HttpClient httpClient, String clientUri) { AttestationClientBuilder builder = new AttestationClientBuilder().endpoint(clientUri); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()) .tokenValidationOptions(new AttestationTokenValidationOptions() .setValidateExpiresOn(false) .setValidateNotBefore(false)); } else if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isPlaybackMode()) { builder.httpClient(httpClient); } return builder; } /** * Retrieve an attestationClientBuilder for the specified HTTP client and client URI * * @param httpClient - HTTP client ot be used for the attestation client. * @param clientUri - Client base URI to access the service. * @return Returns an attestation client builder corresponding to the httpClient and clientUri. */ AttestationAdministrationClientBuilder getAttestationAdministrationBuilder(HttpClient httpClient, String clientUri) { AttestationAdministrationClientBuilder builder = new AttestationAdministrationClientBuilder() .endpoint(clientUri); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isPlaybackMode()) { builder.tokenValidationOptions(new AttestationTokenValidationOptions() .setValidationSlack(Duration.ofSeconds(10))) .credential(new ClientSecretCredentialBuilder() .clientSecret(Configuration.getGlobalConfiguration().get("ATTESTATION_CLIENT_SECRET")) .clientId(Configuration.getGlobalConfiguration().get("ATTESTATION_CLIENT_ID")) .tenantId(Configuration.getGlobalConfiguration().get("ATTESTATION_TENANT_ID")) .httpClient(httpClient).build()) .httpClient(httpClient); } else { builder.tokenValidationOptions(new AttestationTokenValidationOptions() .setValidateExpiresOn(false) .setValidateNotBefore(false)) .credential(new MockTokenCredential()); } return builder; } /** * Retrieve the signing certificate used for the isolated attestation instance. * * @return Returns a base64 encoded X.509 certificate used to sign policy documents. */ static String getIsolatedSigningCertificateBase64() { return TEST_MODE == TestMode.PLAYBACK ? readResource("isolatedSigningCertificate") : Configuration.getGlobalConfiguration().get("isolatedSigningCertificate"); } protected static X509Certificate getIsolatedSigningCertificate() { String base64Certificate = getIsolatedSigningCertificateBase64(); return X509CertUtils.parse(Base64.getDecoder().decode(base64Certificate)); } /** * Retrieve the signing key used for the isolated attestation instance. * * @return Returns a base64 encoded RSA Key used to sign policy documents. */ static PrivateKey privateKeyFromBase64(String base64) { byte[] signingKey = Base64.getDecoder().decode(base64); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(signingKey); KeyFactory keyFactory; try { keyFactory = KeyFactory.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { throw LOGGER.logThrowableAsError(new RuntimeException(e)); } PrivateKey privateKey; try { privateKey = keyFactory.generatePrivate(keySpec); } catch (InvalidKeySpecException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } return privateKey; } protected static PrivateKey getIsolatedSigningKey() { return privateKeyFromBase64(getIsolatedSigningKeyBase64()); } private static String readResource(String resourceName) { try (InputStream resource = AttestationClientTestBase.class.getClassLoader().getResourceAsStream(resourceName); BufferedReader reader = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8))) { return reader.readLine(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new RuntimeException(e)); } } /** * Retrieves a certificate which can be used to sign attestation policies. * * @return Returns a base64 encoded X.509 certificate which can be used to sign attestation policies. */ static String getPolicySigningCertificate0Base64() { return TEST_MODE == TestMode.PLAYBACK ? readResource("policySigningCertificate0") : Configuration.getGlobalConfiguration().get("policySigningCertificate0"); } static String getPolicySigningKey0Base64() { return TEST_MODE == TestMode.PLAYBACK ? readResource("policySigningKey0") : Configuration.getGlobalConfiguration().get("policySigningKey0"); } protected static X509Certificate getPolicySigningCertificate0() { return X509CertUtils.parse(Base64.getDecoder().decode(getPolicySigningCertificate0Base64())); } protected static PrivateKey getPolicySigningKey0() { return privateKeyFromBase64(getPolicySigningKey0Base64()); } protected static KeyPair createKeyPair(String algorithm) throws NoSuchAlgorithmException { KeyPairGenerator keyGen; if ("EC".equals(algorithm)) { keyGen = KeyPairGenerator.getInstance(algorithm, Security.getProvider("SunEC")); } else { keyGen = KeyPairGenerator.getInstance(algorithm); } if ("RSA".equals(algorithm)) { keyGen.initialize(2048); } return keyGen.generateKeyPair(); } @SuppressWarnings("deprecation") protected static X509Certificate createSelfSignedCertificate(String subjectName, KeyPair certificateKey) throws CertificateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { final X509V3CertificateGenerator generator = new X509V3CertificateGenerator(); generator.setIssuerDN(new X500Principal("CN=" + subjectName)); generator.setSubjectDN(new X500Principal("CN=" + subjectName)); generator.setPublicKey(certificateKey.getPublic()); if (certificateKey.getPublic().getAlgorithm().equals("EC")) { generator.setSignatureAlgorithm("SHA256WITHECDSA"); } else { generator.setSignatureAlgorithm("SHA256WITHRSA"); } generator.setSerialNumber(BigInteger.valueOf(Math.abs(new Random().nextInt()))); generator.setNotBefore(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant())); generator.setNotAfter(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().plus(1, ChronoUnit.DAYS))); generator.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); return generator.generate(certificateKey.getPrivate()); } /** * Returns the location in which the tests are running. * * @return returns the location in which the tests are running. */ private static String getLocationShortName() { return TEST_MODE == TestMode.PLAYBACK ? "wus" : Configuration.getGlobalConfiguration().get("locationShortName"); } /** * Returns the url associated with the isolated MAA instance. * * @return the url associated with the isolated MAA instance. */ private static String getIsolatedUrl() { return TEST_MODE == TestMode.PLAYBACK ? "https: : Configuration.getGlobalConfiguration().get("ATTESTATION_ISOLATED_URL"); } /** * Returns the url associated with the AAD MAA instance. * * @return the url associated with the AAD MAA instance. */ private static String getAadUrl() { return TEST_MODE == TestMode.PLAYBACK ? "https: } /** * Returns the set of clients to be used to test the attestation service. * * @return a stream of Argument objects associated with each of the regions on which to run the attestation test. */ static Stream<Arguments> getAttestationClients() { final String regionShortName = getLocationShortName(); return getHttpClients().flatMap(httpClient -> Stream.of( Arguments.of(httpClient, "https: Arguments.of(httpClient, getIsolatedUrl()), Arguments.of(httpClient, getAadUrl()))); } /** * Returns the set of clients and attestation types used for attestation policy APIs. * * @return a stream of Argument objects associated with each of the regions on which to run the attestation test. */ static Stream<Arguments> getPolicyClients() { return getAttestationClients().flatMap(clientParams -> Stream.of( Arguments.of(clientParams.get()[0], clientParams.get()[1], AttestationType.OPEN_ENCLAVE), Arguments.of(clientParams.get()[0], clientParams.get()[1], AttestationType.TPM), Arguments.of(clientParams.get()[0], clientParams.get()[1], AttestationType.SGX_ENCLAVE))); } }
class AttestationClientTestBase extends TestProxyTestBase { protected static final SerializerAdapter ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); protected static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; protected static final ClientLogger LOGGER = new ClientLogger(AttestationClientTestBase.class); protected Tracer tracer; @Override protected void beforeTest() { super.beforeTest(); if (interceptorManager.isPlaybackMode()) { interceptorManager.addMatchers(Collections.singletonList(new CustomMatcher() .setHeadersKeyOnlyMatch(Collections.singletonList("Authorization")))); } } private static final TestMode TEST_MODE = getTestModeLocal(); static TestMode getTestModeLocal() { final String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); if (azureTestMode != null) { try { return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); } catch (IllegalArgumentException e) { LOGGER.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); return TestMode.PLAYBACK; } } LOGGER.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); return TestMode.PLAYBACK; } enum ClientTypes { SHARED, ISOLATED, AAD, } @BeforeAll public static void beforeAll() { TestBase.setupClass(); } @Override @BeforeEach public void setupTest(TestInfo testInfo) { GlobalOpenTelemetry.resetForTest(); super.setupTest(testInfo); String testMethod = testInfo.getTestMethod().isPresent() ? testInfo.getTestMethod().get().getName() : testInfo.getDisplayName(); tracer = configureLoggingExporter(testMethod); } @Override @AfterEach public void teardownTest(TestInfo testInfo) { GlobalOpenTelemetry.resetForTest(); super.teardownTest(testInfo); } @SuppressWarnings({"deprecation", "resource"}) public static Tracer configureLoggingExporter(String testName) { SdkTracerProvider tracerProvider = SdkTracerProvider.builder() .addSpanProcessor(SimpleSpanProcessor.create(new LoggingSpanExporter())) .build(); return OpenTelemetrySdk.builder() .setTracerProvider(tracerProvider) .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())) .buildAndRegisterGlobal() .getTracer(testName); } /** * Determine the Attestation instance type based on the client URI provided. * * @param clientUri - URI for the attestation client. * @return the ClientTypes corresponding to the specified client URI. */ static ClientTypes classifyClient(String clientUri) { assertNotNull(clientUri); String regionShortName = getLocationShortName(); String sharedUri = "https: if (sharedUri.equals(clientUri)) { return ClientTypes.SHARED; } else if (getIsolatedUrl().equals(clientUri)) { return ClientTypes.ISOLATED; } else if (getAadUrl().equals(clientUri)) { return ClientTypes.AAD; } throw new IllegalArgumentException(); } /** * Retrieve an authenticated attestationClientBuilder for the specified HTTP client and client URI * * @param httpClient - HTTP client ot be used for the attestation client. * @param clientUri - Client base URI to access the service. * @return Returns an attestation client builder corresponding to the httpClient and clientUri. */ AttestationClientBuilder getAuthenticatedAttestationBuilder(HttpClient httpClient, String clientUri) { AttestationClientBuilder builder = getAttestationBuilder(httpClient, clientUri); if (!interceptorManager.isPlaybackMode()) { builder.credential(new ClientSecretCredentialBuilder() .clientSecret(Configuration.getGlobalConfiguration().get("ATTESTATION_CLIENT_SECRET")) .clientId(Configuration.getGlobalConfiguration().get("ATTESTATION_CLIENT_ID")) .tenantId(Configuration.getGlobalConfiguration().get("ATTESTATION_TENANT_ID")) .httpClient(httpClient).build()); } else { builder.credential(new MockTokenCredential()); } return builder; } /** * Retrieve an attestationClientBuilder for the specified HTTP client and client URI * * @param httpClient - HTTP client ot be used for the attestation client. * @param clientUri - Client base URI to access the service. * @return Returns an attestation client builder corresponding to the httpClient and clientUri. */ AttestationClientBuilder getAttestationBuilder(HttpClient httpClient, String clientUri) { AttestationClientBuilder builder = new AttestationClientBuilder().endpoint(clientUri); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()) .tokenValidationOptions(new AttestationTokenValidationOptions() .setValidateExpiresOn(false) .setValidateNotBefore(false)); } else if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isPlaybackMode()) { builder.httpClient(httpClient); } return builder; } /** * Retrieve an attestationClientBuilder for the specified HTTP client and client URI * * @param httpClient - HTTP client ot be used for the attestation client. * @param clientUri - Client base URI to access the service. * @return Returns an attestation client builder corresponding to the httpClient and clientUri. */ AttestationAdministrationClientBuilder getAttestationAdministrationBuilder(HttpClient httpClient, String clientUri) { AttestationAdministrationClientBuilder builder = new AttestationAdministrationClientBuilder() .endpoint(clientUri); if (interceptorManager.isPlaybackMode()) { builder.httpClient(interceptorManager.getPlaybackClient()); } else if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isPlaybackMode()) { builder.tokenValidationOptions(new AttestationTokenValidationOptions() .setValidationSlack(Duration.ofSeconds(10))) .credential(new ClientSecretCredentialBuilder() .clientSecret(Configuration.getGlobalConfiguration().get("ATTESTATION_CLIENT_SECRET")) .clientId(Configuration.getGlobalConfiguration().get("ATTESTATION_CLIENT_ID")) .tenantId(Configuration.getGlobalConfiguration().get("ATTESTATION_TENANT_ID")) .httpClient(httpClient).build()) .httpClient(httpClient); } else { builder.tokenValidationOptions(new AttestationTokenValidationOptions() .setValidateExpiresOn(false) .setValidateNotBefore(false)) .credential(new MockTokenCredential()); } return builder; } /** * Retrieve the signing certificate used for the isolated attestation instance. * * @return Returns a base64 encoded X.509 certificate used to sign policy documents. */ static String getIsolatedSigningCertificateBase64() { return TEST_MODE == TestMode.PLAYBACK ? readResource("isolatedSigningCertificate") : Configuration.getGlobalConfiguration().get("isolatedSigningCertificate"); } protected static X509Certificate getIsolatedSigningCertificate() { String base64Certificate = getIsolatedSigningCertificateBase64(); return X509CertUtils.parse(Base64.getDecoder().decode(base64Certificate)); } /** * Retrieve the signing key used for the isolated attestation instance. * * @return Returns a base64 encoded RSA Key used to sign policy documents. */ static PrivateKey privateKeyFromBase64(String base64) { byte[] signingKey = Base64.getDecoder().decode(base64); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(signingKey); KeyFactory keyFactory; try { keyFactory = KeyFactory.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { throw LOGGER.logThrowableAsError(new RuntimeException(e)); } PrivateKey privateKey; try { privateKey = keyFactory.generatePrivate(keySpec); } catch (InvalidKeySpecException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } return privateKey; } protected static PrivateKey getIsolatedSigningKey() { return privateKeyFromBase64(getIsolatedSigningKeyBase64()); } private static String readResource(String resourceName) { try (InputStream resource = AttestationClientTestBase.class.getClassLoader().getResourceAsStream(resourceName); BufferedReader reader = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8))) { return reader.readLine(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new RuntimeException(e)); } } /** * Retrieves a certificate which can be used to sign attestation policies. * * @return Returns a base64 encoded X.509 certificate which can be used to sign attestation policies. */ static String getPolicySigningCertificate0Base64() { return TEST_MODE == TestMode.PLAYBACK ? readResource("policySigningCertificate0") : Configuration.getGlobalConfiguration().get("policySigningCertificate0"); } static String getPolicySigningKey0Base64() { return TEST_MODE == TestMode.PLAYBACK ? readResource("policySigningKey0") : Configuration.getGlobalConfiguration().get("policySigningKey0"); } protected static X509Certificate getPolicySigningCertificate0() { return X509CertUtils.parse(Base64.getDecoder().decode(getPolicySigningCertificate0Base64())); } protected static PrivateKey getPolicySigningKey0() { return privateKeyFromBase64(getPolicySigningKey0Base64()); } protected static KeyPair createKeyPair(String algorithm) throws NoSuchAlgorithmException { KeyPairGenerator keyGen; if ("EC".equals(algorithm)) { keyGen = KeyPairGenerator.getInstance(algorithm, Security.getProvider("SunEC")); } else { keyGen = KeyPairGenerator.getInstance(algorithm); } if ("RSA".equals(algorithm)) { keyGen.initialize(2048); } return keyGen.generateKeyPair(); } @SuppressWarnings("deprecation") protected static X509Certificate createSelfSignedCertificate(String subjectName, KeyPair certificateKey) throws CertificateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { final X509V3CertificateGenerator generator = new X509V3CertificateGenerator(); generator.setIssuerDN(new X500Principal("CN=" + subjectName)); generator.setSubjectDN(new X500Principal("CN=" + subjectName)); generator.setPublicKey(certificateKey.getPublic()); if (certificateKey.getPublic().getAlgorithm().equals("EC")) { generator.setSignatureAlgorithm("SHA256WITHECDSA"); } else { generator.setSignatureAlgorithm("SHA256WITHRSA"); } generator.setSerialNumber(BigInteger.valueOf(Math.abs(new Random().nextInt()))); generator.setNotBefore(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant())); generator.setNotAfter(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().plus(1, ChronoUnit.DAYS))); generator.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); return generator.generate(certificateKey.getPrivate()); } /** * Returns the location in which the tests are running. * * @return returns the location in which the tests are running. */ private static String getLocationShortName() { return TEST_MODE == TestMode.PLAYBACK ? "wus" : Configuration.getGlobalConfiguration().get("locationShortName"); } /** * Returns the url associated with the isolated MAA instance. * * @return the url associated with the isolated MAA instance. */ private static String getIsolatedUrl() { return TEST_MODE == TestMode.PLAYBACK ? "https: : Configuration.getGlobalConfiguration().get("ATTESTATION_ISOLATED_URL"); } /** * Returns the url associated with the AAD MAA instance. * * @return the url associated with the AAD MAA instance. */ private static String getAadUrl() { return TEST_MODE == TestMode.PLAYBACK ? "https: } /** * Returns the set of clients to be used to test the attestation service. * * @return a stream of Argument objects associated with each of the regions on which to run the attestation test. */ static Stream<Arguments> getAttestationClients() { final String regionShortName = getLocationShortName(); return getHttpClients().flatMap(httpClient -> Stream.of( Arguments.of(httpClient, "https: Arguments.of(httpClient, getIsolatedUrl()), Arguments.of(httpClient, getAadUrl()))); } /** * Returns the set of clients and attestation types used for attestation policy APIs. * * @return a stream of Argument objects associated with each of the regions on which to run the attestation test. */ static Stream<Arguments> getPolicyClients() { return getAttestationClients().flatMap(clientParams -> Stream.of( Arguments.of(clientParams.get()[0], clientParams.get()[1], AttestationType.OPEN_ENCLAVE), Arguments.of(clientParams.get()[0], clientParams.get()[1], AttestationType.TPM), Arguments.of(clientParams.get()[0], clientParams.get()[1], AttestationType.SGX_ENCLAVE))); } }
Why are we wrapping this when the API is checked with `IOException`? This seems to be wrapping needlessly.
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { try { channel.write(ByteBuffer.wrap(bodyBytes)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; try { while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } close(); } }
} catch (IOException ex) {
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { channel.write(ByteBuffer.wrap(bodyBytes)); } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } close(); } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
I think this all should be changed to have the IOException be thrown without wrapping as an UncheckedIOException as that is breaking the contract defined in the Javadocs. ```java /** * Transfers body bytes to the {@link WritableByteChannel}. * @param channel The destination {@link WritableByteChannel}. * @throws IOException When I/O operation fails. * @throws NullPointerException When {@code channel} is null. */ ```
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { try { channel.write(ByteBuffer.wrap(bodyBytes)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; try { while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } close(); } }
} catch (IOException ex) {
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { channel.write(ByteBuffer.wrap(bodyBytes)); } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } close(); } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
We have https://github.com/Azure/azure-sdk-for-java/pull/35699/files/0ef8450c81d072a29ca34ae6c506b597426401ac#diff-f629e0a19b7fd0b632aa2a927f88201bee3711b0635222a8c87149ce7ddeb80aR85-R86 two lines to catch the IOException type, also there are other places in the file. Should I remove the try catch statement as well?
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { try { channel.write(ByteBuffer.wrap(bodyBytes)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; try { while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } close(); } }
} catch (IOException ex) {
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { channel.write(ByteBuffer.wrap(bodyBytes)); } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } close(); } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
I didn't realize we never shipped stabIe jdkclient. In this case, I'm fully in favor of breaking change anywhere we already wrap `IOException` (in methods that supposed to throw it)
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { try { channel.write(ByteBuffer.wrap(bodyBytes)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; try { while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } close(); } }
} catch (IOException ex) {
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { channel.write(ByteBuffer.wrap(bodyBytes)); } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } close(); } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
If I'm going to guess what happened is when this was initially being implemented `LOGGER.logThrowableAsError(ioException)` caused Spotbugs to incorrectly flag this as a bug (https://github.com/spotbugs/spotbugs/issues/1219) so `LOGGER.logExceptionAsError` was used wrapping with an UncheckedIOException. Instead, the logging should happen on one line and then the exception gets thrown without wrapping (and suppress our Checkstyle rule for logging exceptions [though it shouldn't raise this as a bug but I think it does]).
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { try { channel.write(ByteBuffer.wrap(bodyBytes)); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; try { while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } close(); } }
} catch (IOException ex) {
public void writeBodyTo(WritableByteChannel channel) throws IOException { if (bodyBytes != null) { channel.write(ByteBuffer.wrap(bodyBytes)); } else { int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { channel.write(ByteBuffer.wrap(data, 0, nRead)); } close(); } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
class JdkHttpResponseSync extends JdkHttpResponseBase { private static final ClientLogger LOGGER = new ClientLogger(JdkHttpResponseSync.class); private BinaryData binaryData = null; public static final int STREAM_READ_SIZE = 8192; private final InputStream bodyStream; private byte[] bodyBytes; private volatile boolean disposed = false; JdkHttpResponseSync(final HttpRequest request, int statusCode, HttpHeaders headers, byte[] bytes) { super(request, statusCode, headers); this.bodyStream = null; this.bodyBytes = bytes; } JdkHttpResponseSync(final HttpRequest request, java.net.http.HttpResponse<InputStream> streamResponse) { super(request, streamResponse.statusCode(), fromJdkHttpHeaders(streamResponse.headers())); this.bodyStream = streamResponse.body(); this.bodyBytes = null; } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes != null) { return Mono.fromSupplier(() -> ByteBuffer.wrap(bodyBytes)).flux(); } else { return FluxUtil.toFluxByteBuffer(bodyStream).doFinally(ignored -> close()); } } @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes != null) { return Mono.just(bodyBytes); } else { return super.getBodyAsByteArray(); } } @Override public BinaryData getBodyAsBinaryData() { if (bodyBytes != null) { return BinaryData.fromBytes(bodyBytes); } else { return getBinaryData(); } } @Override @Override public void close() { if (!disposed && bodyStream != null) { disposed = true; try { bodyStream.close(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } } @Override public HttpResponse buffer() { if (bodyBytes == null) { bodyBytes = getBytes(); close(); } return this; } private byte[] getBytes() { try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[STREAM_READ_SIZE]; while ((nRead = bodyStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return dataOutputBuffer.toByteArray(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } private BinaryData getBinaryData() { if (binaryData == null) { binaryData = BinaryData.fromStream(bodyStream); } return binaryData; } }
I don't think it can ever be null, but I like the check, lets keep it.
public void mergeClientSideRequestStatistics(ClientSideRequestStatistics other) { if (other == null) { return; } this.mergeAddressResolutionStatistics(other.addressResolutionStatistics); this.mergeContactedReplicas(other.contactedReplicas); this.mergeFailedReplica(other.failedReplicas); this.mergeLocationEndpointsContacted(other.locationEndpointsContacted); this.mergeRegionsContacted(other.regionsContacted); this.mergeStartTime(other.requestStartTimeUTC); this.mergeEndTime(other.requestEndTimeUTC); this.mergeSupplementalResponses(other.supplementalResponseStatisticsList); this.mergeResponseStatistics(other.responseStatisticsList); this.requestPayloadSizeInBytes = Math.max(this.requestPayloadSizeInBytes, other.requestPayloadSizeInBytes); if (this.retryContext == null) { this.retryContext = other.retryContext; } else { this.retryContext.merge(other.retryContext); } }
this.mergeStartTime(other.requestStartTimeUTC);
public void mergeClientSideRequestStatistics(ClientSideRequestStatistics other) { if (other == null) { return; } this.mergeAddressResolutionStatistics(other.addressResolutionStatistics); this.mergeContactedReplicas(other.contactedReplicas); this.mergeFailedReplica(other.failedReplicas); this.mergeLocationEndpointsContacted(other.locationEndpointsContacted); this.mergeRegionsContacted(other.regionsContacted); this.mergeStartTime(other.requestStartTimeUTC); this.mergeEndTime(other.requestEndTimeUTC); this.mergeSupplementalResponses(other.supplementalResponseStatisticsList); this.mergeResponseStatistics(other.responseStatisticsList); this.requestPayloadSizeInBytes = Math.max(this.requestPayloadSizeInBytes, other.requestPayloadSizeInBytes); if (this.retryContext == null) { this.retryContext = other.retryContext; } else { this.retryContext.merge(other.retryContext); } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext.DiagnosticsClientConfig diagnosticsClientConfig; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private FaultInjectionRequestContext requestContext; private GatewayStatistics gatewayStatistics; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; private int requestPayloadSizeInBytes = 0; private final String userAgent; private double samplingRateSnapshot = 1; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientConfig = diagnosticsClientContext.getConfig(); this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); this.requestPayloadSizeInBytes = 0; this.userAgent = diagnosticsClientContext.getUserAgent(); this.samplingRateSnapshot = 1; } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientConfig = toBeCloned.diagnosticsClientConfig; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); this.requestPayloadSizeInBytes = toBeCloned.requestPayloadSizeInBytes; this.userAgent = toBeCloned.userAgent; this.samplingRateSnapshot = toBeCloned.samplingRateSnapshot; } @JsonIgnore public Duration getDuration() { if (requestStartTimeUTC == null || requestEndTimeUTC == null || requestEndTimeUTC.isBefore(requestStartTimeUTC)) { return null; } if (requestStartTimeUTC == requestEndTimeUTC) { return Duration.ZERO; } return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public Instant getRequestEndTimeUTC() { return requestEndTimeUTC; } public DiagnosticsClientContext.DiagnosticsClientConfig getDiagnosticsClientConfig() { return diagnosticsClientConfig; } public void recordResponse(RxDocumentServiceRequest request, StoreResultDiagnostics storeResultDiagnostics, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestStartTimeUTC = this.extractRequestStartTime(storeResultDiagnostics); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = storeResultDiagnostics; storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); storeResponseStatistics.requestSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); activityId = request.getActivityId().toString(); this.requestPayloadSizeInBytes = request.getContentLength(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null) { storeResponseStatistics.regionName = globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType()); this.regionsContacted.add(storeResponseStatistics.regionName); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponseDiagnostics storeResponseDiagnostics, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } this.gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); this.requestPayloadSizeInBytes = rxDocumentServiceRequest.getContentLength(); } this.gatewayStatistics.statusCode = storeResponseDiagnostics.getStatusCode(); this.gatewayStatistics.subStatusCode = storeResponseDiagnostics.getSubStatusCode(); this.gatewayStatistics.sessionToken = storeResponseDiagnostics.getSessionTokenAsString(); this.gatewayStatistics.requestCharge = storeResponseDiagnostics.getRequestCharge(); this.gatewayStatistics.requestTimeline = storeResponseDiagnostics.getRequestTimeline(); this.gatewayStatistics.partitionKeyRangeId = storeResponseDiagnostics.getPartitionKeyRangeId(); this.gatewayStatistics.exceptionMessage = storeResponseDiagnostics.getExceptionMessage(); this.gatewayStatistics.exceptionResponseHeaders = storeResponseDiagnostics.getExceptionResponseHeaders(); this.gatewayStatistics.responsePayloadSizeInBytes = storeResponseDiagnostics.getResponsePayloadLength(); this.activityId = storeResponseDiagnostics.getActivityId(); } } public int getRequestPayloadSizeInBytes() { return this.requestPayloadSizeInBytes; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = UUID .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd(String identifier, String exceptionMessage) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.exceptionMessage = exceptionMessage; resolutionStatistics.inflightRequest = false; } } private void mergeContactedReplicas(List<URI> otherContactedReplicas) { if (otherContactedReplicas == null) { return; } if (this.contactedReplicas == null || this.contactedReplicas.isEmpty()) { this.contactedReplicas = otherContactedReplicas; return; } LinkedHashSet<URI> totalContactedReplicas = new LinkedHashSet<>(); totalContactedReplicas.addAll(otherContactedReplicas); totalContactedReplicas.addAll(this.contactedReplicas); this.setContactedReplicas(new ArrayList<>(totalContactedReplicas)); } private void mergeSupplementalResponses(List<StoreResponseStatistics> other) { if (other == null) { return; } if (this.supplementalResponseStatisticsList == null || this.supplementalResponseStatisticsList.isEmpty()) { this.supplementalResponseStatisticsList = other; return; } this.supplementalResponseStatisticsList.addAll(other); } private void mergeResponseStatistics(List<StoreResponseStatistics> other) { if (other == null) { return; } if (this.responseStatisticsList == null || this.responseStatisticsList.isEmpty()) { this.responseStatisticsList = other; return; } this.responseStatisticsList.addAll(other); this.responseStatisticsList.sort( (StoreResponseStatistics left, StoreResponseStatistics right) -> { if (left == null || left.requestStartTimeUTC == null) { return -1; } if (right == null || right.requestStartTimeUTC == null) { return 1; } return left.requestStartTimeUTC.compareTo(right.requestStartTimeUTC); } ); } private void mergeAddressResolutionStatistics( Map<String, AddressResolutionStatistics> otherAddressResolutionStatistics) { if (otherAddressResolutionStatistics == null) { return; } if (this.addressResolutionStatistics == null || this.addressResolutionStatistics.isEmpty()) { this.addressResolutionStatistics = otherAddressResolutionStatistics; return; } for (Map.Entry<String, AddressResolutionStatistics> pair : otherAddressResolutionStatistics.entrySet()) { this.addressResolutionStatistics.putIfAbsent( pair.getKey(), pair.getValue()); } } private void mergeFailedReplica(Set<URI> other) { if (other == null) { return; } if (this.failedReplicas == null || this.failedReplicas.isEmpty()) { this.failedReplicas = other; return; } for (URI uri : other) { this.failedReplicas.add(uri); } } private void mergeLocationEndpointsContacted(Set<URI> other) { if (other == null) { return; } if (this.locationEndpointsContacted == null || this.locationEndpointsContacted.isEmpty()) { this.locationEndpointsContacted = other; return; } for (URI uri : other) { this.locationEndpointsContacted.add(uri); } } private void mergeRegionsContacted(Set<String> other) { if (other == null) { return; } if (this.regionsContacted == null || this.regionsContacted.isEmpty()) { this.regionsContacted = other; return; } for (String region : other) { this.regionsContacted.add(region); } } private void mergeStartTime(Instant other) { if (other == null) { return; } if (this.requestStartTimeUTC == null || this.requestStartTimeUTC.isAfter(other)) { this.requestStartTimeUTC = other; } } private void mergeEndTime(Instant other) { if (other == null || this.requestEndTimeUTC == null) { return; } if (this.requestEndTimeUTC.isBefore(other)) { this.requestEndTimeUTC = other; } } private Instant extractRequestStartTime(StoreResultDiagnostics storeResultDiagnostics){ StoreResponseDiagnostics storeResponseDiagnostics = storeResultDiagnostics.getStoreResponseDiagnostics(); if(storeResponseDiagnostics == null) { return null; } RequestTimeline requestTimeline = storeResponseDiagnostics.getRequestTimeline(); return requestTimeline != null ? requestTimeline.getRequestStartTimeUTC() : null; } public void recordContributingPointOperation(ClientSideRequestStatistics other) { this.mergeClientSideRequestStatistics(other); } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } @JsonIgnore public String getUserAgent() { return this.userAgent; } public int getMaxResponsePayloadSizeInBytes() { if (responseStatisticsList == null || responseStatisticsList.isEmpty()) { if (this.gatewayStatistics != null) { return this.gatewayStatistics.responsePayloadSizeInBytes; } return 0; } int maxResponsePayloadSizeInBytes = 0; int currentResponsePayloadSizeInBytes = 0; for (StoreResponseStatistics responseDiagnostic : responseStatisticsList) { StoreResultDiagnostics storeResultDiagnostics; StoreResponseDiagnostics storeResponseDiagnostics; if ((storeResultDiagnostics = responseDiagnostic.getStoreResult()) != null && (storeResponseDiagnostics = storeResultDiagnostics.getStoreResponseDiagnostics()) != null && (currentResponsePayloadSizeInBytes = storeResponseDiagnostics.getResponsePayloadLength()) > maxResponsePayloadSizeInBytes) { maxResponsePayloadSizeInBytes = currentResponsePayloadSizeInBytes; } } return maxResponsePayloadSizeInBytes; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public String getActivityId() { return this.activityId; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public GatewayStatistics getGatewayStatistics() { return gatewayStatistics; } public ClientSideRequestStatistics setSamplingRateSnapshot(double samplingRateSnapshot) { this.samplingRateSnapshot = samplingRateSnapshot; return this; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResultDiagnostics.StoreResultDiagnosticsSerializer.class) private StoreResultDiagnostics storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestStartTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; @JsonSerialize private String requestSessionToken; @JsonIgnore private String regionName; public StoreResultDiagnostics getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } public String getRegionName() { return regionName; } public String getRequestSessionToken() { return requestSessionToken; } @JsonIgnore public Duration getDuration() { if (requestStartTimeUTC == null || requestResponseTimeUTC == null || requestResponseTimeUTC.isBefore(requestStartTimeUTC)) { return null; } if (requestStartTimeUTC == requestResponseTimeUTC) { return Duration.ZERO; } return Duration.between(requestStartTimeUTC, requestResponseTimeUTC); } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); Duration duration = statistics .getDuration(); long requestLatency = duration != null ? duration.toMillis() : 0; generator.writeStringField("userAgent", statistics.userAgent); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics); generator.writeObjectField("samplingRateSnapshot", statistics.samplingRateSnapshot); try { CosmosDiagnosticsSystemUsageSnapshot systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientConfig); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String exceptionMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getExceptionMessage() { return exceptionMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } } public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private double requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; private String exceptionMessage; private String exceptionResponseHeaders; private int responsePayloadSizeInBytes; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public double getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } public String getExceptionMessage() { return exceptionMessage; } public String getExceptionResponseHeaders() { return exceptionResponseHeaders; } public int getResponsePayloadSizeInBytes() { return this.responsePayloadSizeInBytes; } } public static CosmosDiagnosticsSystemUsageSnapshot fetchSystemInformation() { Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; String systemCpu = CpuMemoryMonitor .getCpuLoad() .toString(); return ImplementationBridgeHelpers .CosmosDiagnosticsContextHelper .getCosmosDiagnosticsContextAccessor() .createSystemUsageSnapshot( systemCpu, totalMemory - freeMemory + " KB", (maxMemory - (totalMemory - freeMemory)) + " KB", runtime.availableProcessors()); } }
class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; private final DiagnosticsClientContext.DiagnosticsClientConfig diagnosticsClientConfig; private String activityId; private List<StoreResponseStatistics> responseStatisticsList; private List<StoreResponseStatistics> supplementalResponseStatisticsList; private Map<String, AddressResolutionStatistics> addressResolutionStatistics; private List<URI> contactedReplicas; private Set<URI> failedReplicas; private Instant requestStartTimeUTC; private Instant requestEndTimeUTC; private Set<String> regionsContacted; private Set<URI> locationEndpointsContacted; private RetryContext retryContext; private FaultInjectionRequestContext requestContext; private List<GatewayStatistics> gatewayStatisticsList; private MetadataDiagnosticsContext metadataDiagnosticsContext; private SerializationDiagnosticsContext serializationDiagnosticsContext; private int requestPayloadSizeInBytes = 0; private final String userAgent; private double samplingRateSnapshot = 1; public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext) { this.diagnosticsClientConfig = diagnosticsClientContext.getConfig(); this.requestStartTimeUTC = Instant.now(); this.requestEndTimeUTC = Instant.now(); this.responseStatisticsList = new ArrayList<>(); this.supplementalResponseStatisticsList = new ArrayList<>(); this.gatewayStatisticsList = new ArrayList<>(); this.addressResolutionStatistics = new HashMap<>(); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>()); this.failedReplicas = Collections.synchronizedSet(new HashSet<>()); this.regionsContacted = Collections.synchronizedSet(new HashSet<>()); this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>()); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(); this.retryContext = new RetryContext(); this.requestPayloadSizeInBytes = 0; this.userAgent = diagnosticsClientContext.getUserAgent(); this.samplingRateSnapshot = 1; } public ClientSideRequestStatistics(ClientSideRequestStatistics toBeCloned) { this.diagnosticsClientConfig = toBeCloned.diagnosticsClientConfig; this.requestStartTimeUTC = toBeCloned.requestStartTimeUTC; this.requestEndTimeUTC = toBeCloned.requestEndTimeUTC; this.responseStatisticsList = new ArrayList<>(toBeCloned.responseStatisticsList); this.supplementalResponseStatisticsList = new ArrayList<>(toBeCloned.supplementalResponseStatisticsList); this.gatewayStatisticsList = new ArrayList<>(toBeCloned.gatewayStatisticsList); this.addressResolutionStatistics = new HashMap<>(toBeCloned.addressResolutionStatistics); this.contactedReplicas = Collections.synchronizedList(new ArrayList<>(toBeCloned.contactedReplicas)); this.failedReplicas = Collections.synchronizedSet(new HashSet<>(toBeCloned.failedReplicas)); this.regionsContacted = Collections.synchronizedSet(new HashSet<>(toBeCloned.regionsContacted)); this.locationEndpointsContacted = Collections.synchronizedSet( new HashSet<>(toBeCloned.locationEndpointsContacted)); this.metadataDiagnosticsContext = new MetadataDiagnosticsContext(toBeCloned.metadataDiagnosticsContext); this.serializationDiagnosticsContext = new SerializationDiagnosticsContext(toBeCloned.serializationDiagnosticsContext); this.retryContext = new RetryContext(toBeCloned.retryContext); this.requestPayloadSizeInBytes = toBeCloned.requestPayloadSizeInBytes; this.userAgent = toBeCloned.userAgent; this.samplingRateSnapshot = toBeCloned.samplingRateSnapshot; } @JsonIgnore public Duration getDuration() { if (requestStartTimeUTC == null || requestEndTimeUTC == null || requestEndTimeUTC.isBefore(requestStartTimeUTC)) { return null; } if (requestStartTimeUTC == requestEndTimeUTC) { return Duration.ZERO; } return Duration.between(requestStartTimeUTC, requestEndTimeUTC); } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public Instant getRequestEndTimeUTC() { return requestEndTimeUTC; } public DiagnosticsClientContext.DiagnosticsClientConfig getDiagnosticsClientConfig() { return diagnosticsClientConfig; } public void recordResponse(RxDocumentServiceRequest request, StoreResultDiagnostics storeResultDiagnostics, GlobalEndpointManager globalEndpointManager) { Objects.requireNonNull(request, "request is required and cannot be null."); Instant responseTime = Instant.now(); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); storeResponseStatistics.requestStartTimeUTC = this.extractRequestStartTime(storeResultDiagnostics); storeResponseStatistics.requestResponseTimeUTC = responseTime; storeResponseStatistics.storeResult = storeResultDiagnostics; storeResponseStatistics.requestOperationType = request.getOperationType(); storeResponseStatistics.requestResourceType = request.getResourceType(); storeResponseStatistics.requestSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); activityId = request.getActivityId().toString(); this.requestPayloadSizeInBytes = request.getContentLength(); URI locationEndPoint = null; if (request.requestContext != null) { if (request.requestContext.locationEndpointToRoute != null) { locationEndPoint = request.requestContext.locationEndpointToRoute; } } synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } if (locationEndPoint != null) { storeResponseStatistics.regionName = globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType()); this.regionsContacted.add(storeResponseStatistics.regionName); this.locationEndpointsContacted.add(locationEndPoint); } if (storeResponseStatistics.requestOperationType == OperationType.Head || storeResponseStatistics.requestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.add(storeResponseStatistics); } else { this.responseStatisticsList.add(storeResponseStatistics); } } } public void recordGatewayResponse( RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponseDiagnostics storeResponseDiagnostics, GlobalEndpointManager globalEndpointManager) { Instant responseTime = Instant.now(); synchronized (this) { if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } URI locationEndPoint = null; if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; } this.recordRetryContextEndTime(); if (locationEndPoint != null) { this.regionsContacted.add(globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType())); this.locationEndpointsContacted.add(locationEndPoint); } GatewayStatistics gatewayStatistics = new GatewayStatistics(); if (rxDocumentServiceRequest != null) { gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType(); gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType(); this.requestPayloadSizeInBytes = rxDocumentServiceRequest.getContentLength(); } gatewayStatistics.statusCode = storeResponseDiagnostics.getStatusCode(); gatewayStatistics.subStatusCode = storeResponseDiagnostics.getSubStatusCode(); gatewayStatistics.sessionToken = storeResponseDiagnostics.getSessionTokenAsString(); gatewayStatistics.requestCharge = storeResponseDiagnostics.getRequestCharge(); gatewayStatistics.requestTimeline = storeResponseDiagnostics.getRequestTimeline(); gatewayStatistics.partitionKeyRangeId = storeResponseDiagnostics.getPartitionKeyRangeId(); gatewayStatistics.exceptionMessage = storeResponseDiagnostics.getExceptionMessage(); gatewayStatistics.exceptionResponseHeaders = storeResponseDiagnostics.getExceptionResponseHeaders(); gatewayStatistics.responsePayloadSizeInBytes = storeResponseDiagnostics.getResponsePayloadLength(); gatewayStatistics.faultInjectionRuleId = storeResponseDiagnostics.getFaultInjectionRuleId(); gatewayStatistics.faultInjectionEvaluationResults = storeResponseDiagnostics.getFaultInjectionEvaluationResults(); this.activityId = storeResponseDiagnostics.getActivityId(); this.gatewayStatisticsList.add(gatewayStatistics); } } public int getRequestPayloadSizeInBytes() { return this.requestPayloadSizeInBytes; } public String recordAddressResolutionStart( URI targetEndpoint, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { String identifier = UUID .randomUUID() .toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); resolutionStatistics.startTimeUTC = Instant.now(); resolutionStatistics.endTimeUTC = null; resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString(); resolutionStatistics.forceRefresh = forceRefresh; resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh; synchronized (this) { this.addressResolutionStatistics.put(identifier, resolutionStatistics); } return identifier; } public void recordAddressResolutionEnd( String identifier, String exceptionMessage, String faultInjectionId, List<String> faultInjectionEvaluationResult) { if (StringUtils.isEmpty(identifier)) { return; } Instant responseTime = Instant.now(); synchronized (this) { if (!this.addressResolutionStatistics.containsKey(identifier)) { throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start " + "before calling end"); } if (responseTime.isAfter(this.requestEndTimeUTC)) { this.requestEndTimeUTC = responseTime; } AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier); resolutionStatistics.endTimeUTC = responseTime; resolutionStatistics.exceptionMessage = exceptionMessage; resolutionStatistics.inflightRequest = false; resolutionStatistics.faultInjectionRuleId = faultInjectionId; resolutionStatistics.faultInjectionEvaluationResults = faultInjectionEvaluationResult; } } private void mergeContactedReplicas(List<URI> otherContactedReplicas) { if (otherContactedReplicas == null) { return; } if (this.contactedReplicas == null || this.contactedReplicas.isEmpty()) { this.contactedReplicas = otherContactedReplicas; return; } LinkedHashSet<URI> totalContactedReplicas = new LinkedHashSet<>(); totalContactedReplicas.addAll(otherContactedReplicas); totalContactedReplicas.addAll(this.contactedReplicas); this.setContactedReplicas(new ArrayList<>(totalContactedReplicas)); } private void mergeSupplementalResponses(List<StoreResponseStatistics> other) { if (other == null) { return; } if (this.supplementalResponseStatisticsList == null || this.supplementalResponseStatisticsList.isEmpty()) { this.supplementalResponseStatisticsList = other; return; } this.supplementalResponseStatisticsList.addAll(other); } private void mergeResponseStatistics(List<StoreResponseStatistics> other) { if (other == null) { return; } if (this.responseStatisticsList == null || this.responseStatisticsList.isEmpty()) { this.responseStatisticsList = other; return; } this.responseStatisticsList.addAll(other); this.responseStatisticsList.sort( (StoreResponseStatistics left, StoreResponseStatistics right) -> { if (left == null || left.requestStartTimeUTC == null) { return -1; } if (right == null || right.requestStartTimeUTC == null) { return 1; } return left.requestStartTimeUTC.compareTo(right.requestStartTimeUTC); } ); } private void mergeAddressResolutionStatistics( Map<String, AddressResolutionStatistics> otherAddressResolutionStatistics) { if (otherAddressResolutionStatistics == null) { return; } if (this.addressResolutionStatistics == null || this.addressResolutionStatistics.isEmpty()) { this.addressResolutionStatistics = otherAddressResolutionStatistics; return; } for (Map.Entry<String, AddressResolutionStatistics> pair : otherAddressResolutionStatistics.entrySet()) { this.addressResolutionStatistics.putIfAbsent( pair.getKey(), pair.getValue()); } } private void mergeFailedReplica(Set<URI> other) { if (other == null) { return; } if (this.failedReplicas == null || this.failedReplicas.isEmpty()) { this.failedReplicas = other; return; } for (URI uri : other) { this.failedReplicas.add(uri); } } private void mergeLocationEndpointsContacted(Set<URI> other) { if (other == null) { return; } if (this.locationEndpointsContacted == null || this.locationEndpointsContacted.isEmpty()) { this.locationEndpointsContacted = other; return; } for (URI uri : other) { this.locationEndpointsContacted.add(uri); } } private void mergeRegionsContacted(Set<String> other) { if (other == null) { return; } if (this.regionsContacted == null || this.regionsContacted.isEmpty()) { this.regionsContacted = other; return; } for (String region : other) { this.regionsContacted.add(region); } } private void mergeStartTime(Instant other) { if (other == null) { return; } if (this.requestStartTimeUTC == null || this.requestStartTimeUTC.isAfter(other)) { this.requestStartTimeUTC = other; } } private void mergeEndTime(Instant other) { if (other == null || this.requestEndTimeUTC == null) { return; } if (this.requestEndTimeUTC.isBefore(other)) { this.requestEndTimeUTC = other; } } private Instant extractRequestStartTime(StoreResultDiagnostics storeResultDiagnostics){ StoreResponseDiagnostics storeResponseDiagnostics = storeResultDiagnostics.getStoreResponseDiagnostics(); if(storeResponseDiagnostics == null) { return null; } RequestTimeline requestTimeline = storeResponseDiagnostics.getRequestTimeline(); return requestTimeline != null ? requestTimeline.getRequestStartTimeUTC() : null; } public void recordContributingPointOperation(ClientSideRequestStatistics other) { this.mergeClientSideRequestStatistics(other); } public List<URI> getContactedReplicas() { return contactedReplicas; } public void setContactedReplicas(List<URI> contactedReplicas) { this.contactedReplicas = Collections.synchronizedList(contactedReplicas); } public Set<URI> getFailedReplicas() { return failedReplicas; } public void setFailedReplicas(Set<URI> failedReplicas) { this.failedReplicas = Collections.synchronizedSet(failedReplicas); } public Set<String> getContactedRegionNames() { return regionsContacted; } public void setRegionsContacted(Set<String> regionsContacted) { this.regionsContacted = Collections.synchronizedSet(regionsContacted); } public Set<URI> getLocationEndpointsContacted() { return locationEndpointsContacted; } public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) { this.locationEndpointsContacted = locationEndpointsContacted; } public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){ return this.metadataDiagnosticsContext; } public SerializationDiagnosticsContext getSerializationDiagnosticsContext() { return this.serializationDiagnosticsContext; } public void recordRetryContextEndTime() { this.retryContext.updateEndTime(); } public RetryContext getRetryContext() { return retryContext; } public List<StoreResponseStatistics> getResponseStatisticsList() { return responseStatisticsList; } @JsonIgnore public String getUserAgent() { return this.userAgent; } public int getMaxResponsePayloadSizeInBytes() { if (responseStatisticsList == null || responseStatisticsList.isEmpty()) { return this.getMaxResponsePayloadSizeInBytesFromGateway(); } int maxResponsePayloadSizeInBytes = 0; int currentResponsePayloadSizeInBytes = 0; for (StoreResponseStatistics responseDiagnostic : responseStatisticsList) { StoreResultDiagnostics storeResultDiagnostics; StoreResponseDiagnostics storeResponseDiagnostics; if ((storeResultDiagnostics = responseDiagnostic.getStoreResult()) != null && (storeResponseDiagnostics = storeResultDiagnostics.getStoreResponseDiagnostics()) != null && (currentResponsePayloadSizeInBytes = storeResponseDiagnostics.getResponsePayloadLength()) > maxResponsePayloadSizeInBytes) { maxResponsePayloadSizeInBytes = currentResponsePayloadSizeInBytes; } } return maxResponsePayloadSizeInBytes; } private int getMaxResponsePayloadSizeInBytesFromGateway() { if (this.gatewayStatisticsList == null || this.gatewayStatisticsList.size() == 0) { return 0; } int maxResponsePayloadSizeInBytes = 0; for (GatewayStatistics gatewayStatistics : this.gatewayStatisticsList) { maxResponsePayloadSizeInBytes = Math.max(maxResponsePayloadSizeInBytes, gatewayStatistics.responsePayloadSizeInBytes); } return maxResponsePayloadSizeInBytes; } public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() { return supplementalResponseStatisticsList; } public String getActivityId() { return this.activityId; } public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() { return addressResolutionStatistics; } public List<GatewayStatistics> getGatewayStatisticsList() { return this.gatewayStatisticsList; } public ClientSideRequestStatistics setSamplingRateSnapshot(double samplingRateSnapshot) { this.samplingRateSnapshot = samplingRateSnapshot; return this; } public static class StoreResponseStatistics { @JsonSerialize(using = StoreResultDiagnostics.StoreResultDiagnosticsSerializer.class) private StoreResultDiagnostics storeResult; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestResponseTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant requestStartTimeUTC; @JsonSerialize private ResourceType requestResourceType; @JsonSerialize private OperationType requestOperationType; @JsonSerialize private String requestSessionToken; @JsonIgnore private String regionName; public StoreResultDiagnostics getStoreResult() { return storeResult; } public Instant getRequestResponseTimeUTC() { return requestResponseTimeUTC; } public Instant getRequestStartTimeUTC() { return requestStartTimeUTC; } public ResourceType getRequestResourceType() { return requestResourceType; } public OperationType getRequestOperationType() { return requestOperationType; } public String getRegionName() { return regionName; } public String getRequestSessionToken() { return requestSessionToken; } @JsonIgnore public Duration getDuration() { if (requestStartTimeUTC == null || requestResponseTimeUTC == null || requestResponseTimeUTC.isBefore(requestStartTimeUTC)) { return null; } if (requestStartTimeUTC == requestResponseTimeUTC) { return Duration.ZERO; } return Duration.between(requestStartTimeUTC, requestResponseTimeUTC); } } public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> { private static final long serialVersionUID = -2746532297176812860L; ClientSideRequestStatisticsSerializer() { super(ClientSideRequestStatistics.class); } @Override public void serialize( ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); Duration duration = statistics .getDuration(); long requestLatency = duration != null ? duration.toMillis() : 0; generator.writeStringField("userAgent", statistics.userAgent); generator.writeStringField("activityId", statistics.activityId); generator.writeNumberField("requestLatencyInMs", requestLatency); generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC)); generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC)); generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList); generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList)); generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics); generator.writeObjectField("regionsContacted", statistics.regionsContacted); generator.writeObjectField("retryContext", statistics.retryContext); generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext()); generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext()); generator.writeObjectField("gatewayStatisticsList", statistics.gatewayStatisticsList); generator.writeObjectField("samplingRateSnapshot", statistics.samplingRateSnapshot); try { CosmosDiagnosticsSystemUsageSnapshot systemInformation = fetchSystemInformation(); generator.writeObjectField("systemInformation", systemInformation); } catch (Exception e) { } generator.writeObjectField("clientCfgs", statistics.diagnosticsClientConfig); generator.writeEndObject(); } } public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) { int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size(); int initialIndex = Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0); if (initialIndex != 0) { List<StoreResponseStatistics> subList = supplementalResponseStatisticsList .subList(initialIndex, supplementalResponseStatisticsListCount); return subList; } return supplementalResponseStatisticsList; } public static class AddressResolutionStatistics { @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant startTimeUTC; @JsonSerialize(using = DiagnosticsInstantSerializer.class) private Instant endTimeUTC; @JsonSerialize private String targetEndpoint; @JsonSerialize private String exceptionMessage; @JsonSerialize private boolean forceRefresh; @JsonSerialize private boolean forceCollectionRoutingMapRefresh; @JsonInclude(JsonInclude.Include.NON_NULL) private String faultInjectionRuleId; @JsonInclude(JsonInclude.Include.NON_NULL) private List<String> faultInjectionEvaluationResults; @JsonSerialize private boolean inflightRequest = true; public Instant getStartTimeUTC() { return startTimeUTC; } public Instant getEndTimeUTC() { return endTimeUTC; } public String getTargetEndpoint() { return targetEndpoint; } public String getExceptionMessage() { return exceptionMessage; } public boolean isInflightRequest() { return inflightRequest; } public boolean isForceRefresh() { return forceRefresh; } public boolean isForceCollectionRoutingMapRefresh() { return forceCollectionRoutingMapRefresh; } public String getFaultInjectionRuleId() { return faultInjectionRuleId; } public List<String> getFaultInjectionEvaluationResults() { return faultInjectionEvaluationResults; } } @JsonSerialize(using = GatewayStatistics.GatewayStatisticsSerializer.class) public static class GatewayStatistics { private String sessionToken; private OperationType operationType; private ResourceType resourceType; private int statusCode; private int subStatusCode; private double requestCharge; private RequestTimeline requestTimeline; private String partitionKeyRangeId; private String exceptionMessage; private String exceptionResponseHeaders; private int responsePayloadSizeInBytes; private String faultInjectionRuleId; private List<String> faultInjectionEvaluationResults; public String getSessionToken() { return sessionToken; } public OperationType getOperationType() { return operationType; } public int getStatusCode() { return statusCode; } public int getSubStatusCode() { return subStatusCode; } public double getRequestCharge() { return requestCharge; } public RequestTimeline getRequestTimeline() { return requestTimeline; } public ResourceType getResourceType() { return resourceType; } public String getPartitionKeyRangeId() { return partitionKeyRangeId; } public String getExceptionMessage() { return exceptionMessage; } public String getExceptionResponseHeaders() { return exceptionResponseHeaders; } public int getResponsePayloadSizeInBytes() { return this.responsePayloadSizeInBytes; } public String getFaultInjectionRuleId() { return faultInjectionRuleId; } public List<String> getFaultInjectionEvaluationResults() { return faultInjectionEvaluationResults; } public static class GatewayStatisticsSerializer extends StdSerializer<GatewayStatistics> { private static final long serialVersionUID = 1L; public GatewayStatisticsSerializer(){ super(GatewayStatistics.class); } @Override public void serialize(GatewayStatistics gatewayStatistics, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("sessionToken", gatewayStatistics.getSessionToken()); jsonGenerator.writeStringField("operationType", gatewayStatistics.getOperationType().toString()); jsonGenerator.writeStringField("resourceType", gatewayStatistics.getResourceType().toString()); jsonGenerator.writeNumberField("statusCode", gatewayStatistics.getStatusCode()); jsonGenerator.writeNumberField("subStatusCode", gatewayStatistics.getSubStatusCode()); jsonGenerator.writeNumberField("requestCharge", gatewayStatistics.getRequestCharge()); jsonGenerator.writeObjectField("requestTimeline", gatewayStatistics.getRequestTimeline()); jsonGenerator.writeStringField("partitionKeyRangeId", gatewayStatistics.getPartitionKeyRangeId()); jsonGenerator.writeNumberField("responsePayloadSizeInBytes", gatewayStatistics.getResponsePayloadSizeInBytes()); this.writeNonNullStringField(jsonGenerator, "exceptionMessage", gatewayStatistics.getExceptionMessage()); this.writeNonNullStringField(jsonGenerator, "exceptionResponseHeaders", gatewayStatistics.getExceptionResponseHeaders()); this.writeNonNullStringField(jsonGenerator, "faultInjectionRuleId", gatewayStatistics.getFaultInjectionRuleId()); if (StringUtils.isEmpty(gatewayStatistics.getFaultInjectionRuleId())) { this.writeNonEmptyStringArrayField( jsonGenerator, "faultInjectionEvaluationResults", gatewayStatistics.getFaultInjectionEvaluationResults()); } jsonGenerator.writeEndObject(); } private void writeNonNullStringField(JsonGenerator jsonGenerator, String fieldName, String value) throws IOException { if (value == null) { return; } jsonGenerator.writeStringField(fieldName, value); } private void writeNonEmptyStringArrayField(JsonGenerator jsonGenerator, String fieldName, List<String> values) throws IOException { if (values == null || values.isEmpty()) { return; } jsonGenerator.writeObjectField(fieldName, values); } } } public static CosmosDiagnosticsSystemUsageSnapshot fetchSystemInformation() { Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory() / 1024; long freeMemory = runtime.freeMemory() / 1024; long maxMemory = runtime.maxMemory() / 1024; String systemCpu = CpuMemoryMonitor .getCpuLoad() .toString(); return ImplementationBridgeHelpers .CosmosDiagnosticsContextHelper .getCosmosDiagnosticsContextAccessor() .createSystemUsageSnapshot( systemCpu, totalMemory - freeMemory + " KB", (maxMemory - (totalMemory - freeMemory)) + " KB", runtime.availableProcessors()); } }
Emm, we already has getter?
public void canCreateAndUpdateFunctionAppWithContainerSize() { rgName2 = null; webappName1 = generateRandomResourceName("java-function-", 20); String functionDeploymentSlotName = generateRandomResourceName("fds", 15); FunctionApp functionApp1 = appServiceManager.functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .withContainerSize(512) .create(); FunctionDeploymentSlot functionDeploymentSlot = functionApp1.deploymentSlots() .define(functionDeploymentSlotName) .withConfigurationFromParent() .withContainerSize(256) .create(); Assertions.assertEquals(512, functionApp1.containerSize()); Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); functionApp1.update() .withContainerSize(320) .apply(); functionApp1.refresh(); Assertions.assertEquals(320, functionApp1.containerSize()); Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); functionDeploymentSlot.update() .withContainerSize(128) .apply(); functionDeploymentSlot.refresh(); Assertions.assertEquals(128, functionDeploymentSlot.containerSize()); }
Assertions.assertEquals(320, functionApp1.containerSize());
public void canCreateAndUpdateFunctionAppWithContainerSize() { rgName2 = null; webappName1 = generateRandomResourceName("java-function-", 20); String functionDeploymentSlotName = generateRandomResourceName("fds", 15); FunctionApp functionApp1 = appServiceManager.functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .withContainerSize(512) .create(); FunctionDeploymentSlot functionDeploymentSlot = functionApp1.deploymentSlots() .define(functionDeploymentSlotName) .withConfigurationFromParent() .withContainerSize(256) .create(); Assertions.assertEquals(512, functionApp1.containerSize()); Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); functionApp1.update() .withContainerSize(320) .apply(); functionApp1.refresh(); Assertions.assertEquals(320, functionApp1.containerSize()); Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); functionDeploymentSlot.update() .withContainerSize(128) .apply(); functionDeploymentSlot.refresh(); Assertions.assertEquals(128, functionDeploymentSlot.containerSize()); }
class FunctionAppsTests extends AppServiceTest { private String rgName1 = ""; private String rgName2 = ""; private String webappName1 = ""; private String webappName2 = ""; private String webappName3 = ""; private String appServicePlanName1 = ""; private String appServicePlanName2 = ""; private String storageAccountName1 = ""; protected StorageManager storageManager; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { webappName1 = generateRandomResourceName("java-func-", 20); webappName2 = generateRandomResourceName("java-func-", 20); webappName3 = generateRandomResourceName("java-func-", 20); appServicePlanName1 = generateRandomResourceName("java-asp-", 20); appServicePlanName2 = generateRandomResourceName("java-asp-", 20); storageAccountName1 = generateRandomResourceName("javastore", 20); rgName1 = generateRandomResourceName("javacsmrg", 20); rgName2 = generateRandomResourceName("javacsmrg", 20); storageManager = buildManager(StorageManager.class, httpPipeline, profile); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName1 != null) { resourceManager.resourceGroups().beginDeleteByName(rgName1); } if (rgName2 != null) { try { resourceManager.resourceGroups().beginDeleteByName(rgName2); } catch (ManagementException e) { } } } @Test public void canCRUDFunctionApp() throws Exception { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_WEST, plan1.region()); Assertions.assertEquals(new PricingTier("Dynamic", "Y1"), plan1.pricingTier()); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withExistingAppServicePlan(plan1) .withNewResourceGroup(rgName2) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName2) .withNewAppServicePlan(PricingTier.BASIC_B1) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionAppResource functionAppResource3 = getStorageAccount(storageManager, functionApp3); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource3.storageAccount.getKeys().get(0).value(), functionAppResource3.accountKey); FunctionApp functionApp = appServiceManager.functionApps().getByResourceGroup(rgName1, functionApp1.name()); Assertions.assertEquals(functionApp1.id(), functionApp.id()); functionApp = appServiceManager.functionApps().getById(functionApp2.id()); Assertions.assertEquals(functionApp2.name(), functionApp.name()); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); functionApps = appServiceManager.functionApps().listByResourceGroup(rgName2); Assertions.assertEquals(2, TestUtilities.getSize(functionApps)); functionApp2.update().withNewStorageAccount(storageAccountName1, StorageAccountSkuType.STANDARD_LRS).apply(); Assertions.assertEquals(storageAccountName1, functionApp2.storageAccount().name()); FunctionAppResource functionAppResource2 = getStorageAccount(storageManager, functionApp2); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource2.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource2.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions.assertEquals(storageAccountName1, functionAppResource2.storageAccount.name()); Assertions .assertEquals( functionAppResource2.storageAccount.getKeys().get(0).value(), functionAppResource2.accountKey); int numStorageAccountBefore = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); functionApp1.update().withAppSetting("newKey", "newValue").apply(); int numStorageAccountAfter = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); Assertions.assertEquals(numStorageAccountBefore, numStorageAccountAfter); FunctionAppResource functionAppResource1Updated = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1Updated.appSettings.containsKey("newKey")); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1Updated.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_SHARE).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_SHARE).value()); Assertions .assertEquals( functionAppResource1.storageAccount.name(), functionAppResource1Updated.storageAccount.name()); functionApp3.update().withNewAppServicePlan(PricingTier.STANDARD_S2).apply(); Assertions.assertNotEquals(functionApp3.appServicePlanId(), functionApp1.appServicePlanId()); } private static final String FUNCTION_APP_PACKAGE_URL = "https: @Test public void canCRUDLinuxFunctionApp() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_EAST, plan1.region()); Assertions.assertEquals(new PricingTier(SkuName.DYNAMIC.toString(), "Y1"), plan1.pricingTier()); Assertions.assertTrue(plan1.innerModel().reserved()); Assertions .assertTrue( Arrays .asList(functionApp1.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName1) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp2); assertLinuxJava(functionApp2, FunctionRuntimeStack.JAVA_8); AppServicePlan plan2 = appServiceManager.appServicePlans().getById(functionApp2.appServicePlanId()); Assertions.assertNotNull(plan2); Assertions.assertEquals(PricingTier.STANDARD_S1, plan2.pricingTier()); Assertions.assertTrue(plan2.innerModel().reserved()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withExistingLinuxAppServicePlan(plan2) .withExistingResourceGroup(rgName1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp3); assertLinuxJava(functionApp3, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(3, TestUtilities.getSize(functionApps)); PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test public void canCRUDLinuxFunctionAppPremium() { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1"), plan1.pricingTier()); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test @Disabled("Need container registry") public void canCRUDLinuxFunctionAppPremiumDocker() { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withPrivateRegistryImage( "weidxuregistry.azurecr.io/az-func-java:v1", "https: .withCredentials("weidxuregistry", "PASSWORD") .withRuntime("java") .withRuntimeVersion("~3") .create(); if (!isPlaybackMode()) { functionApp1.zipDeploy(new File(FunctionAppsTests.class.getResource("/java-functions.zip").getPath())); } } @Test public void canCRUDLinuxFunctionAppJava11() throws Exception { rgName2 = null; String runtimeVersion = "~4"; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_11) .withRuntimeVersion(runtimeVersion) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_11, runtimeVersion); assertRunning(functionApp1); } @Test public void canCRUDLinuxFunctionAppJava17() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_17) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_17); assertRunning(functionApp1); } @Test private void assertRunning(FunctionApp functionApp) { if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); String name = "linux_function_app"; Response<String> response = curl("https: + "/api/HttpTrigger-Java?name=" + name); Assertions.assertEquals(200, response.getStatusCode()); String body = response.getValue(); Assertions.assertNotNull(body); Assertions.assertTrue(body.contains("Hello, " + name)); } } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack) { return assertLinuxJava(functionApp, stack, null); } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack, String runtimeVersion) { Assertions.assertEquals(stack.getLinuxFxVersion(), functionApp.linuxFxVersion()); Assertions .assertTrue( Arrays .asList(functionApp.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); Assertions.assertTrue(functionApp.innerModel().reserved()); Map<String, AppSetting> appSettings = functionApp.getAppSettings(); Assertions.assertNotNull(appSettings); Assertions.assertNotNull(appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE)); Assertions.assertEquals( stack.runtime(), appSettings.get(KEY_FUNCTIONS_WORKER_RUNTIME).value()); Assertions.assertEquals( runtimeVersion == null ? stack.version() : runtimeVersion, appSettings.get(KEY_FUNCTIONS_EXTENSION_VERSION).value()); return appSettings; } private static final String KEY_AZURE_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String KEY_CONTENT_AZURE_FILE_CONNECTION_STRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String KEY_CONTENT_SHARE = "WEBSITE_CONTENTSHARE"; private static final String KEY_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String KEY_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; private static final String ACCOUNT_NAME_SEGMENT = "AccountName="; private static final String ACCOUNT_KEY_SEGMENT = "AccountKey="; private static class FunctionAppResource { Map<String, AppSetting> appSettings; String accountName; String accountKey; StorageAccount storageAccount; } private static FunctionAppResource getStorageAccount(StorageManager storageManager, FunctionApp functionApp) { FunctionAppResource resource = new FunctionAppResource(); resource.appSettings = functionApp.getAppSettings(); String storageAccountConnectionString = resource.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(); String[] segments = storageAccountConnectionString.split(";"); for (String segment : segments) { if (segment.startsWith(ACCOUNT_NAME_SEGMENT)) { resource.accountName = segment.substring(ACCOUNT_NAME_SEGMENT.length()); } else if (segment.startsWith(ACCOUNT_KEY_SEGMENT)) { resource.accountKey = segment.substring(ACCOUNT_KEY_SEGMENT.length()); } } if (resource.accountName != null) { PagedIterable<StorageAccount> storageAccounts = storageManager.storageAccounts().list(); for (StorageAccount storageAccount : storageAccounts) { if (resource.accountName.equals(storageAccount.name())) { resource.storageAccount = storageAccount; break; } } } return resource; } }
class FunctionAppsTests extends AppServiceTest { private String rgName1 = ""; private String rgName2 = ""; private String webappName1 = ""; private String webappName2 = ""; private String webappName3 = ""; private String appServicePlanName1 = ""; private String appServicePlanName2 = ""; private String storageAccountName1 = ""; protected StorageManager storageManager; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { webappName1 = generateRandomResourceName("java-func-", 20); webappName2 = generateRandomResourceName("java-func-", 20); webappName3 = generateRandomResourceName("java-func-", 20); appServicePlanName1 = generateRandomResourceName("java-asp-", 20); appServicePlanName2 = generateRandomResourceName("java-asp-", 20); storageAccountName1 = generateRandomResourceName("javastore", 20); rgName1 = generateRandomResourceName("javacsmrg", 20); rgName2 = generateRandomResourceName("javacsmrg", 20); storageManager = buildManager(StorageManager.class, httpPipeline, profile); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName1 != null) { resourceManager.resourceGroups().beginDeleteByName(rgName1); } if (rgName2 != null) { try { resourceManager.resourceGroups().beginDeleteByName(rgName2); } catch (ManagementException e) { } } } @Test public void canCRUDFunctionApp() throws Exception { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_WEST, plan1.region()); Assertions.assertEquals(new PricingTier("Dynamic", "Y1"), plan1.pricingTier()); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withExistingAppServicePlan(plan1) .withNewResourceGroup(rgName2) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName2) .withNewAppServicePlan(PricingTier.BASIC_B1) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionAppResource functionAppResource3 = getStorageAccount(storageManager, functionApp3); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource3.storageAccount.getKeys().get(0).value(), functionAppResource3.accountKey); FunctionApp functionApp = appServiceManager.functionApps().getByResourceGroup(rgName1, functionApp1.name()); Assertions.assertEquals(functionApp1.id(), functionApp.id()); functionApp = appServiceManager.functionApps().getById(functionApp2.id()); Assertions.assertEquals(functionApp2.name(), functionApp.name()); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); functionApps = appServiceManager.functionApps().listByResourceGroup(rgName2); Assertions.assertEquals(2, TestUtilities.getSize(functionApps)); functionApp2.update().withNewStorageAccount(storageAccountName1, StorageAccountSkuType.STANDARD_LRS).apply(); Assertions.assertEquals(storageAccountName1, functionApp2.storageAccount().name()); FunctionAppResource functionAppResource2 = getStorageAccount(storageManager, functionApp2); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource2.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource2.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions.assertEquals(storageAccountName1, functionAppResource2.storageAccount.name()); Assertions .assertEquals( functionAppResource2.storageAccount.getKeys().get(0).value(), functionAppResource2.accountKey); int numStorageAccountBefore = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); functionApp1.update().withAppSetting("newKey", "newValue").apply(); int numStorageAccountAfter = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); Assertions.assertEquals(numStorageAccountBefore, numStorageAccountAfter); FunctionAppResource functionAppResource1Updated = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1Updated.appSettings.containsKey("newKey")); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1Updated.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_SHARE).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_SHARE).value()); Assertions .assertEquals( functionAppResource1.storageAccount.name(), functionAppResource1Updated.storageAccount.name()); functionApp3.update().withNewAppServicePlan(PricingTier.STANDARD_S2).apply(); Assertions.assertNotEquals(functionApp3.appServicePlanId(), functionApp1.appServicePlanId()); } private static final String FUNCTION_APP_PACKAGE_URL = "https: @Test public void canCRUDLinuxFunctionApp() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_EAST, plan1.region()); Assertions.assertEquals(new PricingTier(SkuName.DYNAMIC.toString(), "Y1"), plan1.pricingTier()); Assertions.assertTrue(plan1.innerModel().reserved()); Assertions .assertTrue( Arrays .asList(functionApp1.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName1) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp2); assertLinuxJava(functionApp2, FunctionRuntimeStack.JAVA_8); AppServicePlan plan2 = appServiceManager.appServicePlans().getById(functionApp2.appServicePlanId()); Assertions.assertNotNull(plan2); Assertions.assertEquals(PricingTier.STANDARD_S1, plan2.pricingTier()); Assertions.assertTrue(plan2.innerModel().reserved()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withExistingLinuxAppServicePlan(plan2) .withExistingResourceGroup(rgName1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp3); assertLinuxJava(functionApp3, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(3, TestUtilities.getSize(functionApps)); PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test public void canCRUDLinuxFunctionAppPremium() { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1"), plan1.pricingTier()); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test @Disabled("Need container registry") public void canCRUDLinuxFunctionAppPremiumDocker() { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withPrivateRegistryImage( "weidxuregistry.azurecr.io/az-func-java:v1", "https: .withCredentials("weidxuregistry", "PASSWORD") .withRuntime("java") .withRuntimeVersion("~3") .create(); if (!isPlaybackMode()) { functionApp1.zipDeploy(new File(FunctionAppsTests.class.getResource("/java-functions.zip").getPath())); } } @Test public void canCRUDLinuxFunctionAppJava11() throws Exception { rgName2 = null; String runtimeVersion = "~4"; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_11) .withRuntimeVersion(runtimeVersion) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_11, runtimeVersion); assertRunning(functionApp1); } @Test public void canCRUDLinuxFunctionAppJava17() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_17) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_17); assertRunning(functionApp1); } @Test private void assertRunning(FunctionApp functionApp) { if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); String name = "linux_function_app"; Response<String> response = curl("https: + "/api/HttpTrigger-Java?name=" + name); Assertions.assertEquals(200, response.getStatusCode()); String body = response.getValue(); Assertions.assertNotNull(body); Assertions.assertTrue(body.contains("Hello, " + name)); } } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack) { return assertLinuxJava(functionApp, stack, null); } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack, String runtimeVersion) { Assertions.assertEquals(stack.getLinuxFxVersion(), functionApp.linuxFxVersion()); Assertions .assertTrue( Arrays .asList(functionApp.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); Assertions.assertTrue(functionApp.innerModel().reserved()); Map<String, AppSetting> appSettings = functionApp.getAppSettings(); Assertions.assertNotNull(appSettings); Assertions.assertNotNull(appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE)); Assertions.assertEquals( stack.runtime(), appSettings.get(KEY_FUNCTIONS_WORKER_RUNTIME).value()); Assertions.assertEquals( runtimeVersion == null ? stack.version() : runtimeVersion, appSettings.get(KEY_FUNCTIONS_EXTENSION_VERSION).value()); return appSettings; } private static final String KEY_AZURE_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String KEY_CONTENT_AZURE_FILE_CONNECTION_STRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String KEY_CONTENT_SHARE = "WEBSITE_CONTENTSHARE"; private static final String KEY_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String KEY_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; private static final String ACCOUNT_NAME_SEGMENT = "AccountName="; private static final String ACCOUNT_KEY_SEGMENT = "AccountKey="; private static class FunctionAppResource { Map<String, AppSetting> appSettings; String accountName; String accountKey; StorageAccount storageAccount; } private static FunctionAppResource getStorageAccount(StorageManager storageManager, FunctionApp functionApp) { FunctionAppResource resource = new FunctionAppResource(); resource.appSettings = functionApp.getAppSettings(); String storageAccountConnectionString = resource.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(); String[] segments = storageAccountConnectionString.split(";"); for (String segment : segments) { if (segment.startsWith(ACCOUNT_NAME_SEGMENT)) { resource.accountName = segment.substring(ACCOUNT_NAME_SEGMENT.length()); } else if (segment.startsWith(ACCOUNT_KEY_SEGMENT)) { resource.accountKey = segment.substring(ACCOUNT_KEY_SEGMENT.length()); } } if (resource.accountName != null) { PagedIterable<StorageAccount> storageAccounts = storageManager.storageAccounts().list(); for (StorageAccount storageAccount : storageAccounts) { if (resource.accountName.equals(storageAccount.name())) { resource.storageAccount = storageAccount; break; } } } return resource; } }
Yes, we have.
public void canCreateAndUpdateFunctionAppWithContainerSize() { rgName2 = null; webappName1 = generateRandomResourceName("java-function-", 20); String functionDeploymentSlotName = generateRandomResourceName("fds", 15); FunctionApp functionApp1 = appServiceManager.functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .withContainerSize(512) .create(); FunctionDeploymentSlot functionDeploymentSlot = functionApp1.deploymentSlots() .define(functionDeploymentSlotName) .withConfigurationFromParent() .withContainerSize(256) .create(); Assertions.assertEquals(512, functionApp1.containerSize()); Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); functionApp1.update() .withContainerSize(320) .apply(); functionApp1.refresh(); Assertions.assertEquals(320, functionApp1.containerSize()); Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); functionDeploymentSlot.update() .withContainerSize(128) .apply(); functionDeploymentSlot.refresh(); Assertions.assertEquals(128, functionDeploymentSlot.containerSize()); }
Assertions.assertEquals(320, functionApp1.containerSize());
public void canCreateAndUpdateFunctionAppWithContainerSize() { rgName2 = null; webappName1 = generateRandomResourceName("java-function-", 20); String functionDeploymentSlotName = generateRandomResourceName("fds", 15); FunctionApp functionApp1 = appServiceManager.functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .withContainerSize(512) .create(); FunctionDeploymentSlot functionDeploymentSlot = functionApp1.deploymentSlots() .define(functionDeploymentSlotName) .withConfigurationFromParent() .withContainerSize(256) .create(); Assertions.assertEquals(512, functionApp1.containerSize()); Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); functionApp1.update() .withContainerSize(320) .apply(); functionApp1.refresh(); Assertions.assertEquals(320, functionApp1.containerSize()); Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); functionDeploymentSlot.update() .withContainerSize(128) .apply(); functionDeploymentSlot.refresh(); Assertions.assertEquals(128, functionDeploymentSlot.containerSize()); }
class FunctionAppsTests extends AppServiceTest { private String rgName1 = ""; private String rgName2 = ""; private String webappName1 = ""; private String webappName2 = ""; private String webappName3 = ""; private String appServicePlanName1 = ""; private String appServicePlanName2 = ""; private String storageAccountName1 = ""; protected StorageManager storageManager; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { webappName1 = generateRandomResourceName("java-func-", 20); webappName2 = generateRandomResourceName("java-func-", 20); webappName3 = generateRandomResourceName("java-func-", 20); appServicePlanName1 = generateRandomResourceName("java-asp-", 20); appServicePlanName2 = generateRandomResourceName("java-asp-", 20); storageAccountName1 = generateRandomResourceName("javastore", 20); rgName1 = generateRandomResourceName("javacsmrg", 20); rgName2 = generateRandomResourceName("javacsmrg", 20); storageManager = buildManager(StorageManager.class, httpPipeline, profile); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName1 != null) { resourceManager.resourceGroups().beginDeleteByName(rgName1); } if (rgName2 != null) { try { resourceManager.resourceGroups().beginDeleteByName(rgName2); } catch (ManagementException e) { } } } @Test public void canCRUDFunctionApp() throws Exception { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_WEST, plan1.region()); Assertions.assertEquals(new PricingTier("Dynamic", "Y1"), plan1.pricingTier()); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withExistingAppServicePlan(plan1) .withNewResourceGroup(rgName2) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName2) .withNewAppServicePlan(PricingTier.BASIC_B1) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionAppResource functionAppResource3 = getStorageAccount(storageManager, functionApp3); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource3.storageAccount.getKeys().get(0).value(), functionAppResource3.accountKey); FunctionApp functionApp = appServiceManager.functionApps().getByResourceGroup(rgName1, functionApp1.name()); Assertions.assertEquals(functionApp1.id(), functionApp.id()); functionApp = appServiceManager.functionApps().getById(functionApp2.id()); Assertions.assertEquals(functionApp2.name(), functionApp.name()); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); functionApps = appServiceManager.functionApps().listByResourceGroup(rgName2); Assertions.assertEquals(2, TestUtilities.getSize(functionApps)); functionApp2.update().withNewStorageAccount(storageAccountName1, StorageAccountSkuType.STANDARD_LRS).apply(); Assertions.assertEquals(storageAccountName1, functionApp2.storageAccount().name()); FunctionAppResource functionAppResource2 = getStorageAccount(storageManager, functionApp2); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource2.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource2.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions.assertEquals(storageAccountName1, functionAppResource2.storageAccount.name()); Assertions .assertEquals( functionAppResource2.storageAccount.getKeys().get(0).value(), functionAppResource2.accountKey); int numStorageAccountBefore = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); functionApp1.update().withAppSetting("newKey", "newValue").apply(); int numStorageAccountAfter = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); Assertions.assertEquals(numStorageAccountBefore, numStorageAccountAfter); FunctionAppResource functionAppResource1Updated = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1Updated.appSettings.containsKey("newKey")); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1Updated.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_SHARE).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_SHARE).value()); Assertions .assertEquals( functionAppResource1.storageAccount.name(), functionAppResource1Updated.storageAccount.name()); functionApp3.update().withNewAppServicePlan(PricingTier.STANDARD_S2).apply(); Assertions.assertNotEquals(functionApp3.appServicePlanId(), functionApp1.appServicePlanId()); } private static final String FUNCTION_APP_PACKAGE_URL = "https: @Test public void canCRUDLinuxFunctionApp() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_EAST, plan1.region()); Assertions.assertEquals(new PricingTier(SkuName.DYNAMIC.toString(), "Y1"), plan1.pricingTier()); Assertions.assertTrue(plan1.innerModel().reserved()); Assertions .assertTrue( Arrays .asList(functionApp1.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName1) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp2); assertLinuxJava(functionApp2, FunctionRuntimeStack.JAVA_8); AppServicePlan plan2 = appServiceManager.appServicePlans().getById(functionApp2.appServicePlanId()); Assertions.assertNotNull(plan2); Assertions.assertEquals(PricingTier.STANDARD_S1, plan2.pricingTier()); Assertions.assertTrue(plan2.innerModel().reserved()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withExistingLinuxAppServicePlan(plan2) .withExistingResourceGroup(rgName1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp3); assertLinuxJava(functionApp3, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(3, TestUtilities.getSize(functionApps)); PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test public void canCRUDLinuxFunctionAppPremium() { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1"), plan1.pricingTier()); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test @Disabled("Need container registry") public void canCRUDLinuxFunctionAppPremiumDocker() { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withPrivateRegistryImage( "weidxuregistry.azurecr.io/az-func-java:v1", "https: .withCredentials("weidxuregistry", "PASSWORD") .withRuntime("java") .withRuntimeVersion("~3") .create(); if (!isPlaybackMode()) { functionApp1.zipDeploy(new File(FunctionAppsTests.class.getResource("/java-functions.zip").getPath())); } } @Test public void canCRUDLinuxFunctionAppJava11() throws Exception { rgName2 = null; String runtimeVersion = "~4"; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_11) .withRuntimeVersion(runtimeVersion) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_11, runtimeVersion); assertRunning(functionApp1); } @Test public void canCRUDLinuxFunctionAppJava17() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_17) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_17); assertRunning(functionApp1); } @Test private void assertRunning(FunctionApp functionApp) { if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); String name = "linux_function_app"; Response<String> response = curl("https: + "/api/HttpTrigger-Java?name=" + name); Assertions.assertEquals(200, response.getStatusCode()); String body = response.getValue(); Assertions.assertNotNull(body); Assertions.assertTrue(body.contains("Hello, " + name)); } } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack) { return assertLinuxJava(functionApp, stack, null); } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack, String runtimeVersion) { Assertions.assertEquals(stack.getLinuxFxVersion(), functionApp.linuxFxVersion()); Assertions .assertTrue( Arrays .asList(functionApp.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); Assertions.assertTrue(functionApp.innerModel().reserved()); Map<String, AppSetting> appSettings = functionApp.getAppSettings(); Assertions.assertNotNull(appSettings); Assertions.assertNotNull(appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE)); Assertions.assertEquals( stack.runtime(), appSettings.get(KEY_FUNCTIONS_WORKER_RUNTIME).value()); Assertions.assertEquals( runtimeVersion == null ? stack.version() : runtimeVersion, appSettings.get(KEY_FUNCTIONS_EXTENSION_VERSION).value()); return appSettings; } private static final String KEY_AZURE_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String KEY_CONTENT_AZURE_FILE_CONNECTION_STRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String KEY_CONTENT_SHARE = "WEBSITE_CONTENTSHARE"; private static final String KEY_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String KEY_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; private static final String ACCOUNT_NAME_SEGMENT = "AccountName="; private static final String ACCOUNT_KEY_SEGMENT = "AccountKey="; private static class FunctionAppResource { Map<String, AppSetting> appSettings; String accountName; String accountKey; StorageAccount storageAccount; } private static FunctionAppResource getStorageAccount(StorageManager storageManager, FunctionApp functionApp) { FunctionAppResource resource = new FunctionAppResource(); resource.appSettings = functionApp.getAppSettings(); String storageAccountConnectionString = resource.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(); String[] segments = storageAccountConnectionString.split(";"); for (String segment : segments) { if (segment.startsWith(ACCOUNT_NAME_SEGMENT)) { resource.accountName = segment.substring(ACCOUNT_NAME_SEGMENT.length()); } else if (segment.startsWith(ACCOUNT_KEY_SEGMENT)) { resource.accountKey = segment.substring(ACCOUNT_KEY_SEGMENT.length()); } } if (resource.accountName != null) { PagedIterable<StorageAccount> storageAccounts = storageManager.storageAccounts().list(); for (StorageAccount storageAccount : storageAccounts) { if (resource.accountName.equals(storageAccount.name())) { resource.storageAccount = storageAccount; break; } } } return resource; } }
class FunctionAppsTests extends AppServiceTest { private String rgName1 = ""; private String rgName2 = ""; private String webappName1 = ""; private String webappName2 = ""; private String webappName3 = ""; private String appServicePlanName1 = ""; private String appServicePlanName2 = ""; private String storageAccountName1 = ""; protected StorageManager storageManager; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { webappName1 = generateRandomResourceName("java-func-", 20); webappName2 = generateRandomResourceName("java-func-", 20); webappName3 = generateRandomResourceName("java-func-", 20); appServicePlanName1 = generateRandomResourceName("java-asp-", 20); appServicePlanName2 = generateRandomResourceName("java-asp-", 20); storageAccountName1 = generateRandomResourceName("javastore", 20); rgName1 = generateRandomResourceName("javacsmrg", 20); rgName2 = generateRandomResourceName("javacsmrg", 20); storageManager = buildManager(StorageManager.class, httpPipeline, profile); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName1 != null) { resourceManager.resourceGroups().beginDeleteByName(rgName1); } if (rgName2 != null) { try { resourceManager.resourceGroups().beginDeleteByName(rgName2); } catch (ManagementException e) { } } } @Test public void canCRUDFunctionApp() throws Exception { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_WEST, plan1.region()); Assertions.assertEquals(new PricingTier("Dynamic", "Y1"), plan1.pricingTier()); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withExistingAppServicePlan(plan1) .withNewResourceGroup(rgName2) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName2) .withNewAppServicePlan(PricingTier.BASIC_B1) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionAppResource functionAppResource3 = getStorageAccount(storageManager, functionApp3); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource3.storageAccount.getKeys().get(0).value(), functionAppResource3.accountKey); FunctionApp functionApp = appServiceManager.functionApps().getByResourceGroup(rgName1, functionApp1.name()); Assertions.assertEquals(functionApp1.id(), functionApp.id()); functionApp = appServiceManager.functionApps().getById(functionApp2.id()); Assertions.assertEquals(functionApp2.name(), functionApp.name()); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); functionApps = appServiceManager.functionApps().listByResourceGroup(rgName2); Assertions.assertEquals(2, TestUtilities.getSize(functionApps)); functionApp2.update().withNewStorageAccount(storageAccountName1, StorageAccountSkuType.STANDARD_LRS).apply(); Assertions.assertEquals(storageAccountName1, functionApp2.storageAccount().name()); FunctionAppResource functionAppResource2 = getStorageAccount(storageManager, functionApp2); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource2.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource2.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions.assertEquals(storageAccountName1, functionAppResource2.storageAccount.name()); Assertions .assertEquals( functionAppResource2.storageAccount.getKeys().get(0).value(), functionAppResource2.accountKey); int numStorageAccountBefore = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); functionApp1.update().withAppSetting("newKey", "newValue").apply(); int numStorageAccountAfter = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); Assertions.assertEquals(numStorageAccountBefore, numStorageAccountAfter); FunctionAppResource functionAppResource1Updated = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1Updated.appSettings.containsKey("newKey")); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1Updated.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_SHARE).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_SHARE).value()); Assertions .assertEquals( functionAppResource1.storageAccount.name(), functionAppResource1Updated.storageAccount.name()); functionApp3.update().withNewAppServicePlan(PricingTier.STANDARD_S2).apply(); Assertions.assertNotEquals(functionApp3.appServicePlanId(), functionApp1.appServicePlanId()); } private static final String FUNCTION_APP_PACKAGE_URL = "https: @Test public void canCRUDLinuxFunctionApp() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_EAST, plan1.region()); Assertions.assertEquals(new PricingTier(SkuName.DYNAMIC.toString(), "Y1"), plan1.pricingTier()); Assertions.assertTrue(plan1.innerModel().reserved()); Assertions .assertTrue( Arrays .asList(functionApp1.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName1) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp2); assertLinuxJava(functionApp2, FunctionRuntimeStack.JAVA_8); AppServicePlan plan2 = appServiceManager.appServicePlans().getById(functionApp2.appServicePlanId()); Assertions.assertNotNull(plan2); Assertions.assertEquals(PricingTier.STANDARD_S1, plan2.pricingTier()); Assertions.assertTrue(plan2.innerModel().reserved()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withExistingLinuxAppServicePlan(plan2) .withExistingResourceGroup(rgName1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp3); assertLinuxJava(functionApp3, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(3, TestUtilities.getSize(functionApps)); PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test public void canCRUDLinuxFunctionAppPremium() { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1"), plan1.pricingTier()); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test @Disabled("Need container registry") public void canCRUDLinuxFunctionAppPremiumDocker() { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withPrivateRegistryImage( "weidxuregistry.azurecr.io/az-func-java:v1", "https: .withCredentials("weidxuregistry", "PASSWORD") .withRuntime("java") .withRuntimeVersion("~3") .create(); if (!isPlaybackMode()) { functionApp1.zipDeploy(new File(FunctionAppsTests.class.getResource("/java-functions.zip").getPath())); } } @Test public void canCRUDLinuxFunctionAppJava11() throws Exception { rgName2 = null; String runtimeVersion = "~4"; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_11) .withRuntimeVersion(runtimeVersion) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_11, runtimeVersion); assertRunning(functionApp1); } @Test public void canCRUDLinuxFunctionAppJava17() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_17) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_17); assertRunning(functionApp1); } @Test private void assertRunning(FunctionApp functionApp) { if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); String name = "linux_function_app"; Response<String> response = curl("https: + "/api/HttpTrigger-Java?name=" + name); Assertions.assertEquals(200, response.getStatusCode()); String body = response.getValue(); Assertions.assertNotNull(body); Assertions.assertTrue(body.contains("Hello, " + name)); } } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack) { return assertLinuxJava(functionApp, stack, null); } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack, String runtimeVersion) { Assertions.assertEquals(stack.getLinuxFxVersion(), functionApp.linuxFxVersion()); Assertions .assertTrue( Arrays .asList(functionApp.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); Assertions.assertTrue(functionApp.innerModel().reserved()); Map<String, AppSetting> appSettings = functionApp.getAppSettings(); Assertions.assertNotNull(appSettings); Assertions.assertNotNull(appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE)); Assertions.assertEquals( stack.runtime(), appSettings.get(KEY_FUNCTIONS_WORKER_RUNTIME).value()); Assertions.assertEquals( runtimeVersion == null ? stack.version() : runtimeVersion, appSettings.get(KEY_FUNCTIONS_EXTENSION_VERSION).value()); return appSettings; } private static final String KEY_AZURE_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String KEY_CONTENT_AZURE_FILE_CONNECTION_STRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String KEY_CONTENT_SHARE = "WEBSITE_CONTENTSHARE"; private static final String KEY_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String KEY_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; private static final String ACCOUNT_NAME_SEGMENT = "AccountName="; private static final String ACCOUNT_KEY_SEGMENT = "AccountKey="; private static class FunctionAppResource { Map<String, AppSetting> appSettings; String accountName; String accountKey; StorageAccount storageAccount; } private static FunctionAppResource getStorageAccount(StorageManager storageManager, FunctionApp functionApp) { FunctionAppResource resource = new FunctionAppResource(); resource.appSettings = functionApp.getAppSettings(); String storageAccountConnectionString = resource.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(); String[] segments = storageAccountConnectionString.split(";"); for (String segment : segments) { if (segment.startsWith(ACCOUNT_NAME_SEGMENT)) { resource.accountName = segment.substring(ACCOUNT_NAME_SEGMENT.length()); } else if (segment.startsWith(ACCOUNT_KEY_SEGMENT)) { resource.accountKey = segment.substring(ACCOUNT_KEY_SEGMENT.length()); } } if (resource.accountName != null) { PagedIterable<StorageAccount> storageAccounts = storageManager.storageAccounts().list(); for (StorageAccount storageAccount : storageAccounts) { if (resource.accountName.equals(storageAccount.name())) { resource.storageAccount = storageAccount; break; } } } return resource; } }
Please change at other places as well.
public void databaseCreateContainerAsyncSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer(containerProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); }
throwable -> System.out.printf("Container with id : %s already exists \n", containerId)
public void databaseCreateContainerAsyncSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer(containerProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); }
class AsyncContainerCodeSnippets { private final CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildAsyncClient(); private final CosmosClient cosmosClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildClient(); private final CosmosAsyncDatabase cosmosAsyncDatabase = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); private final CosmosAsyncContainer cosmosAsyncContainer = cosmosAsyncDatabase .getContainer("<YOUR CONTAINER NAME>"); private final CosmosContainer cosmosContainer = cosmosClient .getDatabase("<YOUR DATABASE NAME>") .getContainer("<YOUR CONTAINER NAME>"); public void getFeedRangesAsyncSample() { cosmosAsyncContainer.getFeedRanges() .subscribe(feedRanges -> { for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } }); } public void getFeedRangesSample() { List<FeedRange> feedRanges = cosmosContainer.getFeedRanges(); for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } } public void readThroughputAsyncSample() { Mono<ThroughputResponse> throughputResponseMono = cosmosAsyncContainer.readThroughput(); throughputResponseMono.subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void readThroughputSample() { try { ThroughputResponse throughputResponse = cosmosContainer.readThroughput(); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void replaceThroughputAsyncSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); cosmosAsyncContainer.replaceThroughput(throughputProperties) .subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void replaceThroughputSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); try { ThroughputResponse throughputResponse = cosmosContainer.replaceThroughput(throughputProperties); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void queryConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); String query = "SELECT * from c where c.id in (%s)"; try { cosmosAsyncContainer.queryConflicts(query). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void readAllConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); try { cosmosAsyncContainer.readAllConflicts(options). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void patchItemAsyncSample() { Passenger passenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); CosmosPatchOperations cosmosPatchOperations = CosmosPatchOperations.create(); cosmosPatchOperations .add("/departure", "SEA") .increment("/trips", 1); cosmosAsyncContainer.patchItem( passenger.getId(), new PartitionKey(passenger.getId()), cosmosPatchOperations, Passenger.class) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void replaceItemAsyncSample() { Passenger oldPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); Passenger newPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); cosmosAsyncContainer.replaceItem( newPassenger, oldPassenger.getId(), new PartitionKey(oldPassenger.getId()), new CosmosItemRequestOptions()) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void readAllItemsAsyncSample() { String partitionKey = "partitionKey"; cosmosAsyncContainer .readAllItems(new PartitionKey(partitionKey), Passenger.class) .byPage(100) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void readManyAsyncSample() { String passenger1Id = "item1"; String passenger2Id = "item1"; List<CosmosItemIdentity> itemIdentityList = new ArrayList<>(); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger1Id), passenger1Id)); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger2Id), passenger2Id)); cosmosAsyncContainer.readMany(itemIdentityList, Passenger.class) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Mono.empty(); }) .subscribe(); } public void queryChangeFeedSample() { CosmosChangeFeedRequestOptions options = CosmosChangeFeedRequestOptions .createForProcessingFromNow(FeedRange.forFullRange()) .allVersionsAndDeletes(); cosmosAsyncContainer.queryChangeFeed(options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger WHERE Passenger.departure IN ('SEA', 'IND')"; cosmosAsyncContainer.queryItems(query, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSqlQuerySpecSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger p WHERE (p.departure = @departure)"; List<SqlParameter> parameters = Collections.singletonList(new SqlParameter("@departure", "SEA")); SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(query, parameters); cosmosAsyncContainer.queryItems(sqlQuerySpec, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void databaseReadAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.read().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseDeleteAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.delete().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseCreateContainerPropsSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int autoScaleMaxThroughput = 1000; CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoScaleMaxThroughput); cosmosAsyncDatabase.createContainer(containerProperties, throughputProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); } public void databaseCreateContainerThroughputSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int throughput = 1000; CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer( containerProperties, throughput, options ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); } public void databaseCreateContainerPartitionKeyAsyncSample() { String containerId = "passengers"; String partitionKeyPath = "/id"; int autoscaledThroughput = 1000; ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoscaledThroughput); cosmosAsyncDatabase.createContainer( containerId, partitionKeyPath, throughputProperties ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); } }
class AsyncContainerCodeSnippets { private final CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildAsyncClient(); private final CosmosClient cosmosClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildClient(); private final CosmosAsyncDatabase cosmosAsyncDatabase = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); private final CosmosAsyncContainer cosmosAsyncContainer = cosmosAsyncDatabase .getContainer("<YOUR CONTAINER NAME>"); private final CosmosContainer cosmosContainer = cosmosClient .getDatabase("<YOUR DATABASE NAME>") .getContainer("<YOUR CONTAINER NAME>"); public void getFeedRangesAsyncSample() { cosmosAsyncContainer.getFeedRanges() .subscribe(feedRanges -> { for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } }); } public void getFeedRangesSample() { List<FeedRange> feedRanges = cosmosContainer.getFeedRanges(); for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } } public void readThroughputAsyncSample() { Mono<ThroughputResponse> throughputResponseMono = cosmosAsyncContainer.readThroughput(); throughputResponseMono.subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void readThroughputSample() { try { ThroughputResponse throughputResponse = cosmosContainer.readThroughput(); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void replaceThroughputAsyncSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); cosmosAsyncContainer.replaceThroughput(throughputProperties) .subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void replaceThroughputSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); try { ThroughputResponse throughputResponse = cosmosContainer.replaceThroughput(throughputProperties); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void queryConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); String query = "SELECT * from c where c.id in (%s)"; try { cosmosAsyncContainer.queryConflicts(query). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void readAllConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); try { cosmosAsyncContainer.readAllConflicts(options). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void patchItemAsyncSample() { Passenger passenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); CosmosPatchOperations cosmosPatchOperations = CosmosPatchOperations.create(); cosmosPatchOperations .add("/departure", "SEA") .increment("/trips", 1); cosmosAsyncContainer.patchItem( passenger.getId(), new PartitionKey(passenger.getId()), cosmosPatchOperations, Passenger.class) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void replaceItemAsyncSample() { Passenger oldPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); Passenger newPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); cosmosAsyncContainer.replaceItem( newPassenger, oldPassenger.getId(), new PartitionKey(oldPassenger.getId()), new CosmosItemRequestOptions()) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void readAllItemsAsyncSample() { String partitionKey = "partitionKey"; cosmosAsyncContainer .readAllItems(new PartitionKey(partitionKey), Passenger.class) .byPage(100) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void readManyAsyncSample() { String passenger1Id = "item1"; String passenger2Id = "item1"; List<CosmosItemIdentity> itemIdentityList = new ArrayList<>(); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger1Id), passenger1Id)); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger2Id), passenger2Id)); cosmosAsyncContainer.readMany(itemIdentityList, Passenger.class) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Mono.empty(); }) .subscribe(); } public void queryChangeFeedSample() { CosmosChangeFeedRequestOptions options = CosmosChangeFeedRequestOptions .createForProcessingFromNow(FeedRange.forFullRange()) .allVersionsAndDeletes(); cosmosAsyncContainer.queryChangeFeed(options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger WHERE Passenger.departure IN ('SEA', 'IND')"; cosmosAsyncContainer.queryItems(query, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSqlQuerySpecSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger p WHERE (p.departure = @departure)"; List<SqlParameter> parameters = Collections.singletonList(new SqlParameter("@departure", "SEA")); SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(query, parameters); cosmosAsyncContainer.queryItems(sqlQuerySpec, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void databaseReadAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.read().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseDeleteAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.delete().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseCreateContainerPropsSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int autoScaleMaxThroughput = 1000; CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoScaleMaxThroughput); cosmosAsyncDatabase.createContainer(containerProperties, throughputProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); } public void databaseCreateContainerThroughputSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int throughput = 1000; CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer( containerProperties, throughput, options ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); } public void databaseCreateContainerPartitionKeyAsyncSample() { String containerId = "passengers"; String partitionKeyPath = "/id"; int autoscaledThroughput = 1000; ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoscaledThroughput); cosmosAsyncDatabase.createContainer( containerId, partitionKeyPath, throughputProperties ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); } }
Public OpenAI service don't have an endpoint. If use provides `endpoint`, we assume they are targeting the Azure OpenAI service. Else, targeting OpenAI service.
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { KeyCredentialPolicy keyCredentialPolicy; if (endpoint != null) { keyCredentialPolicy = new KeyCredentialPolicy("api-key", keyCredential); } else { keyCredentialPolicy = new KeyCredentialPolicy("Authorization", keyCredential, "Bearer"); } policies.add(keyCredentialPolicy); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; }
if (endpoint != null) {
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { policies.add( useNonAzureOpenAIService() ? new KeyCredentialPolicy("Authorization", keyCredential, "Bearer") : new KeyCredentialPolicy("api-key", keyCredential)); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } @Generated private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { if (this.endpoint != null) { return new OpenAIAsyncClient(buildInnerClient()); } return new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { if (this.endpoint != null) { return new OpenAIClient(buildInnerClient()); } return new OpenAIClient(buildInnerNonAzureOpenAIClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { return useNonAzureOpenAIService() ? new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()) : new OpenAIAsyncClient(buildInnerClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { return useNonAzureOpenAIService() ? new OpenAIClient(buildInnerNonAzureOpenAIClient()) : new OpenAIClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); /** * OpenAI service can be used by either not setting the endpoint or by setting the endpoint to start with * "https: */ private boolean useNonAzureOpenAIService() { return endpoint == null || endpoint.startsWith(OPEN_AI_ENDPOINT); } }
Why do we want to keep this overload? We should delete it as we are still in beta.
public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); }
return this.credential((KeyCredential) azureKeyCredential);
public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { KeyCredentialPolicy keyCredentialPolicy; if (endpoint != null) { keyCredentialPolicy = new KeyCredentialPolicy("api-key", keyCredential); } else { keyCredentialPolicy = new KeyCredentialPolicy("Authorization", keyCredential, "Bearer"); } policies.add(keyCredentialPolicy); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { if (this.endpoint != null) { return new OpenAIAsyncClient(buildInnerClient()); } return new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { if (this.endpoint != null) { return new OpenAIClient(buildInnerClient()); } return new OpenAIClient(buildInnerNonAzureOpenAIClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { policies.add( useNonAzureOpenAIService() ? new KeyCredentialPolicy("Authorization", keyCredential, "Bearer") : new KeyCredentialPolicy("api-key", keyCredential)); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { return useNonAzureOpenAIService() ? new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()) : new OpenAIAsyncClient(buildInnerClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { return useNonAzureOpenAIService() ? new OpenAIClient(buildInnerNonAzureOpenAIClient()) : new OpenAIClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); /** * OpenAI service can be used by either not setting the endpoint or by setting the endpoint to start with * "https: */ private boolean useNonAzureOpenAIService() { return endpoint == null || endpoint.startsWith(OPEN_AI_ENDPOINT); } }
refactor
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(waitForBuildAsync()); }
.flatMap(waitForBuildAsync());
private Mono<String> uploadAndBuildAsync(File source, ResourceUploadDefinition option) { return uploadToStorageAsync(source, option) .then(enqueueBuildAsync(option)) .flatMap(waitForBuildAsync()); }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } private Function<String, Mono<? extends String>> waitForBuildAsync() { AtomicLong pollCount = new AtomicLong(); Duration pollDuration = manager().serviceClient().getDefaultPollInterval(); return buildId -> manager().serviceClient().getBuildServices() .getBuildResultWithResponseAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(response -> { if (pollDuration.multipliedBy(pollCount.get()).compareTo(MAX_BUILD_TIMEOUT) < 0) { BuildResultProvisioningState state = response.getValue().properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return Mono.error(new ManagementException(String.format("Build failed for file: %s, buildId: %s", file.getName(), buildId), new HttpResponseImpl<>(response, client.getSerializerAdapter()))); } } else { return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", file.getName(), buildId), null)); } }).repeatWhenEmpty(longFlux -> longFlux .flatMap( index -> { pollCount.set(index); return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); })); } @SuppressWarnings("BlockingMethodInNonBlockingContext") private class HttpResponseImpl<T> extends HttpResponse { private final Response<T> response; private final SerializerAdapter serializerAdapter; protected HttpResponseImpl(Response<T> response, SerializerAdapter serializerAdapter) { super(response.getRequest()); this.response = response; this.serializerAdapter = serializerAdapter; } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public String getHeaderValue(String header) { return response.getHeaders().getValue(header); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { try { return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } } @Override public Mono<byte[]> getBodyAsByteArray() { try { return Mono.just(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON)); } catch (IOException e) { return Mono.empty(); } } @Override public Mono<String> getBodyAsString() { return Mono.just(serializerAdapter.serializeRaw(response.getValue())); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsString(); } } }
class BuildServiceTask implements FunctionalTaskItem { private final File file; private final boolean sourceCodeTarGz; private final List<String> configFilePatterns; private String module; BuildServiceTask(File file, List<String> configFilePatterns) { this(file, configFilePatterns, false); } BuildServiceTask(File file, List<String> configFilePatterns, boolean sourceCodeTarGz) { this.file = file; this.configFilePatterns = configFilePatterns; this.sourceCodeTarGz = sourceCodeTarGz; } @Override public Mono<Indexable> apply(Context context) { return app().getResourceUploadUrlAsync() .flatMap(option -> uploadAndBuildAsync(file, option) .flatMap(buildId -> { BuildResultUserSourceInfo userSourceInfo = (BuildResultUserSourceInfo) innerModel().properties().source(); userSourceInfo.withBuildResultId(buildId); withConfigFilePatterns(this.configFilePatterns); return Mono.empty(); }).then(context.voidMono())); } private Mono<String> enqueueBuildAsync(ResourceUploadDefinition option) { BuildProperties buildProperties = new BuildProperties() .withBuilder(String.format("%s/buildservices/%s/builders/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withAgentPool(String.format("%s/buildservices/%s/agentPools/%s", service().id(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME)) .withRelativePath(option.relativePath()); if (this.sourceCodeTarGz) { Map<String, String> buildEnv = buildProperties.env() == null ? new HashMap<>() : buildProperties.env(); buildProperties.withEnv(buildEnv); if (module != null) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } return manager().serviceClient().getBuildServices() .createOrUpdateBuildAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } private Function<String, Mono<? extends String>> waitForBuildAsync() { AtomicLong pollCount = new AtomicLong(); Duration pollDuration = manager().serviceClient().getDefaultPollInterval(); return buildId -> manager().serviceClient().getBuildServices() .getBuildResultWithResponseAsync( service().resourceGroupName(), service().name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, parent().name(), ResourceUtils.nameFromResourceId(buildId)) .flatMap(response -> { if (pollDuration.multipliedBy(pollCount.get()).compareTo(MAX_BUILD_TIMEOUT) < 0) { BuildResultProvisioningState state = response.getValue().properties().provisioningState(); if (state == BuildResultProvisioningState.SUCCEEDED) { return Mono.just(buildId); } else if (state == BuildResultProvisioningState.QUEUING || state == BuildResultProvisioningState.BUILDING) { return Mono.empty(); } else { AppPlatformManagementClientImpl client = (AppPlatformManagementClientImpl) manager().serviceClient(); return Mono.error(new ManagementException(String.format("Build failed for file: %s, buildId: %s", file.getName(), buildId), new HttpResponseImpl<>(response, client.getSerializerAdapter()))); } } else { return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", file.getName(), buildId), null)); } }).repeatWhenEmpty(longFlux -> longFlux .flatMap( index -> { pollCount.set(index); return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); })); } @SuppressWarnings("BlockingMethodInNonBlockingContext") private class HttpResponseImpl<T> extends HttpResponse { private final Response<T> response; private final SerializerAdapter serializerAdapter; protected HttpResponseImpl(Response<T> response, SerializerAdapter serializerAdapter) { super(response.getRequest()); this.response = response; this.serializerAdapter = serializerAdapter; } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public String getHeaderValue(String header) { return response.getHeaders().getValue(header); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { try { return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } } @Override public Mono<byte[]> getBodyAsByteArray() { try { return Mono.just(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON)); } catch (IOException e) { return Mono.empty(); } } @Override public Mono<String> getBodyAsString() { return Mono.just(serializerAdapter.serializeRaw(response.getValue())); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsString(); } } }
since we won't be able to drop this method. The workaround approach will be to call the `credential(KeyCredential)` method internally.
public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); }
return this.credential((KeyCredential) azureKeyCredential);
public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } @Generated private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { KeyCredentialPolicy keyCredentialPolicy; if (endpoint != null) { keyCredentialPolicy = new KeyCredentialPolicy("api-key", keyCredential); } else { keyCredentialPolicy = new KeyCredentialPolicy("Authorization", keyCredential, "Bearer"); } policies.add(keyCredentialPolicy); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { if (this.endpoint != null) { return new OpenAIAsyncClient(buildInnerClient()); } return new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { if (this.endpoint != null) { return new OpenAIClient(buildInnerClient()); } return new OpenAIClient(buildInnerNonAzureOpenAIClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { policies.add( useNonAzureOpenAIService() ? new KeyCredentialPolicy("Authorization", keyCredential, "Bearer") : new KeyCredentialPolicy("api-key", keyCredential)); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { return useNonAzureOpenAIService() ? new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()) : new OpenAIAsyncClient(buildInnerClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { return useNonAzureOpenAIService() ? new OpenAIClient(buildInnerNonAzureOpenAIClient()) : new OpenAIClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); /** * OpenAI service can be used by either not setting the endpoint or by setting the endpoint to start with * "https: */ private boolean useNonAzureOpenAIService() { return endpoint == null || endpoint.startsWith(OPEN_AI_ENDPOINT); } }
Thanks for comment. I've fixed error messages
public void databaseCreateContainerAsyncSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer(containerProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); }
throwable -> System.out.printf("Container with id : %s already exists \n", containerId)
public void databaseCreateContainerAsyncSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer(containerProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); }
class AsyncContainerCodeSnippets { private final CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildAsyncClient(); private final CosmosClient cosmosClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildClient(); private final CosmosAsyncDatabase cosmosAsyncDatabase = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); private final CosmosAsyncContainer cosmosAsyncContainer = cosmosAsyncDatabase .getContainer("<YOUR CONTAINER NAME>"); private final CosmosContainer cosmosContainer = cosmosClient .getDatabase("<YOUR DATABASE NAME>") .getContainer("<YOUR CONTAINER NAME>"); public void getFeedRangesAsyncSample() { cosmosAsyncContainer.getFeedRanges() .subscribe(feedRanges -> { for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } }); } public void getFeedRangesSample() { List<FeedRange> feedRanges = cosmosContainer.getFeedRanges(); for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } } public void readThroughputAsyncSample() { Mono<ThroughputResponse> throughputResponseMono = cosmosAsyncContainer.readThroughput(); throughputResponseMono.subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void readThroughputSample() { try { ThroughputResponse throughputResponse = cosmosContainer.readThroughput(); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void replaceThroughputAsyncSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); cosmosAsyncContainer.replaceThroughput(throughputProperties) .subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void replaceThroughputSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); try { ThroughputResponse throughputResponse = cosmosContainer.replaceThroughput(throughputProperties); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void queryConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); String query = "SELECT * from c where c.id in (%s)"; try { cosmosAsyncContainer.queryConflicts(query). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void readAllConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); try { cosmosAsyncContainer.readAllConflicts(options). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void patchItemAsyncSample() { Passenger passenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); CosmosPatchOperations cosmosPatchOperations = CosmosPatchOperations.create(); cosmosPatchOperations .add("/departure", "SEA") .increment("/trips", 1); cosmosAsyncContainer.patchItem( passenger.getId(), new PartitionKey(passenger.getId()), cosmosPatchOperations, Passenger.class) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void replaceItemAsyncSample() { Passenger oldPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); Passenger newPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); cosmosAsyncContainer.replaceItem( newPassenger, oldPassenger.getId(), new PartitionKey(oldPassenger.getId()), new CosmosItemRequestOptions()) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void readAllItemsAsyncSample() { String partitionKey = "partitionKey"; cosmosAsyncContainer .readAllItems(new PartitionKey(partitionKey), Passenger.class) .byPage(100) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void readManyAsyncSample() { String passenger1Id = "item1"; String passenger2Id = "item1"; List<CosmosItemIdentity> itemIdentityList = new ArrayList<>(); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger1Id), passenger1Id)); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger2Id), passenger2Id)); cosmosAsyncContainer.readMany(itemIdentityList, Passenger.class) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Mono.empty(); }) .subscribe(); } public void queryChangeFeedSample() { CosmosChangeFeedRequestOptions options = CosmosChangeFeedRequestOptions .createForProcessingFromNow(FeedRange.forFullRange()) .allVersionsAndDeletes(); cosmosAsyncContainer.queryChangeFeed(options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger WHERE Passenger.departure IN ('SEA', 'IND')"; cosmosAsyncContainer.queryItems(query, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSqlQuerySpecSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger p WHERE (p.departure = @departure)"; List<SqlParameter> parameters = Collections.singletonList(new SqlParameter("@departure", "SEA")); SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(query, parameters); cosmosAsyncContainer.queryItems(sqlQuerySpec, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void databaseReadAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.read().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseDeleteAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.delete().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseCreateContainerPropsSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int autoScaleMaxThroughput = 1000; CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoScaleMaxThroughput); cosmosAsyncDatabase.createContainer(containerProperties, throughputProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); } public void databaseCreateContainerThroughputSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int throughput = 1000; CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer( containerProperties, throughput, options ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); } public void databaseCreateContainerPartitionKeyAsyncSample() { String containerId = "passengers"; String partitionKeyPath = "/id"; int autoscaledThroughput = 1000; ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoscaledThroughput); cosmosAsyncDatabase.createContainer( containerId, partitionKeyPath, throughputProperties ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); } }
class AsyncContainerCodeSnippets { private final CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildAsyncClient(); private final CosmosClient cosmosClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildClient(); private final CosmosAsyncDatabase cosmosAsyncDatabase = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); private final CosmosAsyncContainer cosmosAsyncContainer = cosmosAsyncDatabase .getContainer("<YOUR CONTAINER NAME>"); private final CosmosContainer cosmosContainer = cosmosClient .getDatabase("<YOUR DATABASE NAME>") .getContainer("<YOUR CONTAINER NAME>"); public void getFeedRangesAsyncSample() { cosmosAsyncContainer.getFeedRanges() .subscribe(feedRanges -> { for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } }); } public void getFeedRangesSample() { List<FeedRange> feedRanges = cosmosContainer.getFeedRanges(); for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } } public void readThroughputAsyncSample() { Mono<ThroughputResponse> throughputResponseMono = cosmosAsyncContainer.readThroughput(); throughputResponseMono.subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void readThroughputSample() { try { ThroughputResponse throughputResponse = cosmosContainer.readThroughput(); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void replaceThroughputAsyncSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); cosmosAsyncContainer.replaceThroughput(throughputProperties) .subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void replaceThroughputSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); try { ThroughputResponse throughputResponse = cosmosContainer.replaceThroughput(throughputProperties); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void queryConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); String query = "SELECT * from c where c.id in (%s)"; try { cosmosAsyncContainer.queryConflicts(query). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void readAllConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); try { cosmosAsyncContainer.readAllConflicts(options). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void patchItemAsyncSample() { Passenger passenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); CosmosPatchOperations cosmosPatchOperations = CosmosPatchOperations.create(); cosmosPatchOperations .add("/departure", "SEA") .increment("/trips", 1); cosmosAsyncContainer.patchItem( passenger.getId(), new PartitionKey(passenger.getId()), cosmosPatchOperations, Passenger.class) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void replaceItemAsyncSample() { Passenger oldPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); Passenger newPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); cosmosAsyncContainer.replaceItem( newPassenger, oldPassenger.getId(), new PartitionKey(oldPassenger.getId()), new CosmosItemRequestOptions()) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void readAllItemsAsyncSample() { String partitionKey = "partitionKey"; cosmosAsyncContainer .readAllItems(new PartitionKey(partitionKey), Passenger.class) .byPage(100) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void readManyAsyncSample() { String passenger1Id = "item1"; String passenger2Id = "item1"; List<CosmosItemIdentity> itemIdentityList = new ArrayList<>(); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger1Id), passenger1Id)); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger2Id), passenger2Id)); cosmosAsyncContainer.readMany(itemIdentityList, Passenger.class) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Mono.empty(); }) .subscribe(); } public void queryChangeFeedSample() { CosmosChangeFeedRequestOptions options = CosmosChangeFeedRequestOptions .createForProcessingFromNow(FeedRange.forFullRange()) .allVersionsAndDeletes(); cosmosAsyncContainer.queryChangeFeed(options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger WHERE Passenger.departure IN ('SEA', 'IND')"; cosmosAsyncContainer.queryItems(query, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSqlQuerySpecSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger p WHERE (p.departure = @departure)"; List<SqlParameter> parameters = Collections.singletonList(new SqlParameter("@departure", "SEA")); SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(query, parameters); cosmosAsyncContainer.queryItems(sqlQuerySpec, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void databaseReadAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.read().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseDeleteAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.delete().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseCreateContainerPropsSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int autoScaleMaxThroughput = 1000; CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoScaleMaxThroughput); cosmosAsyncDatabase.createContainer(containerProperties, throughputProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); } public void databaseCreateContainerThroughputSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int throughput = 1000; CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer( containerProperties, throughput, options ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); } public void databaseCreateContainerPartitionKeyAsyncSample() { String containerId = "passengers"; String partitionKeyPath = "/id"; int autoscaledThroughput = 1000; ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoscaledThroughput); cosmosAsyncDatabase.createContainer( containerId, partitionKeyPath, throughputProperties ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); } }
Customers can set the this to public OpenAI endpoint too. So, we shouldn't assume that the presence of endpoint is always for Azure OpenAI - it could be for public OAI.
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { KeyCredentialPolicy keyCredentialPolicy; if (endpoint != null) { keyCredentialPolicy = new KeyCredentialPolicy("api-key", keyCredential); } else { keyCredentialPolicy = new KeyCredentialPolicy("Authorization", keyCredential, "Bearer"); } policies.add(keyCredentialPolicy); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; }
if (endpoint != null) {
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { policies.add( useNonAzureOpenAIService() ? new KeyCredentialPolicy("Authorization", keyCredential, "Bearer") : new KeyCredentialPolicy("api-key", keyCredential)); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { if (this.endpoint != null) { return new OpenAIAsyncClient(buildInnerClient()); } return new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { if (this.endpoint != null) { return new OpenAIClient(buildInnerClient()); } return new OpenAIClient(buildInnerNonAzureOpenAIClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { return useNonAzureOpenAIService() ? new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()) : new OpenAIAsyncClient(buildInnerClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { return useNonAzureOpenAIService() ? new OpenAIClient(buildInnerNonAzureOpenAIClient()) : new OpenAIClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); /** * OpenAI service can be used by either not setting the endpoint or by setting the endpoint to start with * "https: */ private boolean useNonAzureOpenAIService() { return endpoint == null || endpoint.startsWith(OPEN_AI_ENDPOINT); } }
Same here - endpoint can be non-null and still be public OAI.
public OpenAIAsyncClient buildAsyncClient() { if (this.endpoint != null) { return new OpenAIAsyncClient(buildInnerClient()); } return new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()); }
if (this.endpoint != null) {
public OpenAIAsyncClient buildAsyncClient() { return useNonAzureOpenAIService() ? new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()) : new OpenAIAsyncClient(buildInnerClient()); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { KeyCredentialPolicy keyCredentialPolicy; if (endpoint != null) { keyCredentialPolicy = new KeyCredentialPolicy("api-key", keyCredential); } else { keyCredentialPolicy = new KeyCredentialPolicy("Authorization", keyCredential, "Bearer"); } policies.add(keyCredentialPolicy); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { if (this.endpoint != null) { return new OpenAIClient(buildInnerClient()); } return new OpenAIClient(buildInnerNonAzureOpenAIClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { policies.add( useNonAzureOpenAIService() ? new KeyCredentialPolicy("Authorization", keyCredential, "Bearer") : new KeyCredentialPolicy("api-key", keyCredential)); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { return useNonAzureOpenAIService() ? new OpenAIClient(buildInnerNonAzureOpenAIClient()) : new OpenAIClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); /** * OpenAI service can be used by either not setting the endpoint or by setting the endpoint to start with * "https: */ private boolean useNonAzureOpenAIService() { return endpoint == null || endpoint.startsWith(OPEN_AI_ENDPOINT); } }